Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert enumerator to lazy enumerator

Tags:

ruby

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?

like image 884
tokland Avatar asked May 19 '16 09:05

tokland


People also ask

What does the lazy method do to enumerators?

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.

What is enumerator in Ruby?

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.


1 Answers

You can directly call lazy on the array (or enumerator).

[1, 2, 3].lazy
# => #<Enumerator::Lazy: [1, 2, 3]>
like image 102
sawa Avatar answered Oct 09 '22 07:10

sawa