10.9. Enumerators and the next dimension of enumerability

Enumerators are closely related to iterators, but they aren’t the same thing. An iterator is a method that yields one or more values to a code block. An enumerator is an object, not a method.

At heart, an enumerator is a simple enumerable object. It has an each method, and it employs the Enumerable module to define all the usual methods—select, inject, map, and friends—directly on top of its each.

The twist in the plot, though, is how the enumerator’s each method is engineered.

An enumerator isn’t a container object. It has no “natural” basis for an each operation, the way an array does (start at element 0; yield it; go to element 1; yield it; and so on). The each iteration logic of every ...

Get The Well-Grounded Rubyist, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.