Enumerator class is a built-in Ruby object. Its instances and instances of its subclasses have capabilities of internal and external iteration. Enumerator is a descendent class - just like Array, Hash and Range classes - of Enumerable class.

Blockless Each

Arrays, hashes and ranges in Ruby all have an :each method defined. The method does and returns a different thing depending on whether a block was provided to it or not.

[1,2,3].each { |a| print a } # 123 => [1, 2, 3]

[1,2,3].each # => #<Enumerator: ...>

An enumerator has a next method defined which returns subsequent values of the enumerator's underlying data.

an_enum = [1,2,3].each # => #<Enumerator: ...>

an_enum.next # => 1
an_enum.next # => 2
an_enum.next # => 3
an_enum.next # => StopIteration: iteration reached an end

Creating Enumerators with Loops

It is possible to create a custom made enumerator using a method new, a block and a loop.

even_numbers = Enumerator.new do |y|
  a = 0
  loop do
    y << a
    a += 2

even_numbers.next # => 0
even_numbers.next # => 2
even_numbers.next # => 4
even_numbers.next # => 6
even_numbers.next # => 8

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.