Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

Enumerator::Lazy.new

[out E, out R = void] (?::Integer arg0) { (::Enumerator::Yielder arg0) -> R } -> ::Enumerator::Lazy[E, R]
Lazy.new(obj, size=nil) { |yielder, *values| block }

Creates a new Lazy enumerator. When the enumerator is actually enumerated (e.g. by calling force), obj will be enumerated and each value passed to the given block. The block can yield values back using yielder. For example, to create a “filter+map” enumerator:

Example
def filter_map(sequence)
  Lazy.new(sequence) do |yielder, *values|
    result = yield *values
    yielder << result if result
  end
end

filter_map(1..Float::INFINITY) {|i| i*i if i.even?}.first(5)
#=> [4, 16, 36, 64, 100]
See also #chunk #chunk_while also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0