Ruby 2.7 has added Enumerator#produce to generate Enumerator from any custom data-transformation.
Let’s say we want to print the first 10 numbers of fibonacci series.
The code to achieve this would look like:
As shown above, we need to use
in order to achieve the required results.
We can now use
Enumerator#produce in Ruby 2.7
to achieve this in a simpler way:
Enumerator.produce(initial, &block), will produce an infinite sequence
where each next element is calculated
by applying block to previous.
initial is the first sequence element.
We can use
initial value as well.
Enumerator.produce(&block), will produce an infinite sequence.
The first element of the sequence will be the result of calling
the block with no args.
Example of produce without args:
As illustrated above,
produce helps to
produce enumerators with a much cleaner and simpler code.
More information about this feature along with few other examples can be found on Feature #14781.