Convert enumerator to lazy enumerator

An enumerator can be converted to a lazy counter using Enumerator :: Lazy.new , like this (this is an example: at the beginning, I already have a counter, 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 shorter way to do this?

+7
ruby
source share
2 answers

What about:

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

In fact, but the problem is that I start with an enumerator, not an array

This does not change anything:

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

Enumerable#to_enum returns a counter. If you call the call on Enumerable#lazy , the receiver of the second message is the Enumerator returned by the first call.

+4
source share

You can directly call lazy in an array (or enumerator).

 [1, 2, 3].lazy # => #<Enumerator::Lazy: [1, 2, 3]> 
+7
source share

All Articles