tokland tokland - 6 months ago 15
Ruby Question

Convert enumerator to lazy enumerator

An enumerator can be converted into a lazy enumerator using Enumerator::Lazy.new like this (this is an example; at the beginning, I already have an enumerator, not an array):

xs_enum = [1, 2, 3].to_enum
# => #<Enumerator: [1, 2, 3]:each>
xs_lazy_enum = Enumerator::Lazy.new(xs_enum, &:yield)
# => #<Enumerator::Lazy: #<Enumerator: [1, 2, 3]:each>:each>
xs_lazy_enum.force
# => [1, 2, 3]


Is there a more succinct way to do it?

Answer

What about:

[1, 2, 3].to_enum.lazy
# => #<Enumerator::Lazy: ...>

Indeed, but the problem is that I start from an enumerator, not from an array

That doesn't change anything:

enum = (1..10).each
# => #<Enumerator: ...>
enum.lazy
# => #<Enumerator::Lazy: ...>

Enumerable#to_enum returns an enumerator. If you chain a call to Enumerable#lazy the receiver of the second message is the Enumerator returned by the first call.

Comments