Skip to content

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

instance method

Enumerator::Lazy#enum_for

(::Symbol method, *untyped, **untyped) ?{ (?) -> ::Integer } -> ::Enumerator[untyped, untyped]
() ?{ () -> ::Integer } -> ::Enumerator[E, self]
lzy.enum_for(method = :each, *args) → lazy_enum
lzy.enum_for(method = :each, *args) {|*args| block } → lazy_enum

Alias of #to_enum

Similar to Object#to_enum, except it returns a lazy enumerator. This makes it easy to define Enumerable methods that will naturally remain lazy if called from a lazy enumerator.

For example, continuing from the example in Object#to_enum:

Example
# See Object#to_enum for the definition of repeat
r = 1..Float::INFINITY
r.repeat(2).first(5) # => [1, 1, 2, 2, 3]
r.repeat(2).class # => Enumerator
r.repeat(2).map{|n| n ** 2}.first(5) # => endless loop!
# works naturally on lazy enumerator:
r.lazy.repeat(2).class # => Enumerator::Lazy
r.lazy.repeat(2).map{|n| n ** 2}.first(5) # => [1, 1, 4, 4, 9]
See also #to_enum #eager #filter #each_with_index also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0