The question "Meaning of the word yield" mentions the Enumerator::Yielder#yield
method. I haven't used it before, and wonder under what circumstances it would be useful.
Is it mainly useful when you want to create an infinite list of items, such as the Sieve of Eratosthenes, and when you need to use an external iterator?
"How to create an infinite enumerable of Times?" talks about constructing and lazy iterators, but my favorite usage is wrapping an existing Enumerable with additional functionality (any enumerable, without needing to know what it really is, whether it's infinite or not etc).
A trivial example would be implementing the
each_with_index
method (or, more generally,with_index
method):Extending to something not already implemented in the core library, such as cyclically assigning value from a given array to each enumerable element (say, for coloring table rows):
The whole point is that these methods return an
Enumerator
, which you then combine with the usual Enumerable methods, such asselect
,map
,inject
etc.