Skip to content
class method

Enumerator.new

[unchecked out Elem, out Return = void] (?::Integer arg0) { (::Enumerator::Yielder arg0) -> Return } -> ::Enumerator[Elem, Return]
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 .product also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0