Ruby Enumerator

Gary Cordero Rosa
3 min readFeb 21, 2021

An enumerator is a class in ruby that supports internal and external iteratoration, although it looks more like a function that behaves like an iterator. The best part of an enumerator is that they are highly customizable.

(Full definition from Wikipedia): “A generator is a special routine that can be used to control the iteration behaviour of a loop. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.”

We can build an example of an enumerator in many ways, it could be one that iterates over the Fibonacci sequence.

We can move over the series, using the next() method. That means that we can call the next element in the enumerator anytime we want.

Or we can take the first Nth elements from

We add the lazy call because otherwise, ruby would wait for all elements in the series to be generated before slicing the first 5 elements, luckily enumerators have been built smart enough to defer loading of elements until needed if specified with the lazy call in the chain.

We can even take it a little further and do something more advance.

Conclusion

Enumerators are a must-have under your ruby developer toolkit, they take iteration to the next level, letting you have more control over it. You can find more info about enumerator in the ruby documentation.

--

--