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?
Enumerator::Lazy is a special type of Enumerator , that allows constructing chains of operations without evaluating them immediately, and evaluating values on as-needed basis. In order to do so it redefines most of Enumerable methods so that they just construct another lazy enumerator.
Enumerator, specifically, is a class in Ruby that allows both types of iterations – external and internal. Internal iteration refers to the form of iteration which is controlled by the class in question, while external iteration means that the environment or the client controls the way iteration is performed.
You can directly call lazy
on the array (or enumerator).
[1, 2, 3].lazy
# => #<Enumerator::Lazy: [1, 2, 3]>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With