Turning Any Class Into An Enumerator
At the core of any enumerator is the ability to respond to an #each
call. With that in mind, we prepare any class for being turned into an enumerator.
Consider this class SquaresCollection
that allows you to turn an array of integers into an array of its squares.
We can work with this, but it opts out of Ruby's enumerator offerings.
We can, instead, provide an #each
method which allows instances of our SquaresCollection
class to be turned into enumerators.
Here is how we can use it:
The #to_enum
method looks for an #each
method on the instance's class and uses that to create an enumerator.
Last updated