Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Enumerator.new

Enumerator.new(size = nil) { |yielder| ... }

Creates a new Enumerator object, which can be used as an Enumerable.

Iteration is defined by the given block, in which a “yielder” object, given as block parameter, can be used to yield a value by calling the yield method (aliased as <<):

Example
fib = Enumerator.new do |y|
  a = b = 1
  loop do
    y << a
    a, b = b, a + b
  end
end

fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

The optional parameter can be used to specify how to calculate the size in a lazy fashion (see Enumerator#size). It can either be a value or a callable object.

See also .produce #+ also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1