Enumerators

Intro

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
  end
end

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