Iterators

Learn about iterators in Ruby and how they can be chainable.

Iterators are chainable

Methods on arrays and hashes that take a block are also called iterators. We say they iterate over the array, meaning that these methods take each element of the array and do something with it. In Ruby, iterators are chainable, adding functionality on top of each other.

That means that if we don’t pass a block to an iterator method, such as each, collect, or select, then we’ll get an iterator object back. We can then call more methods on these iterator objects and finally pass a block, like so:

Press + to interact
numbers = [1, 2, 3, 4, 5].collect.with_index do |number, index|
number + index
end
p numbers

This prints out:

[1, 3, 5, 7, 9]

What’s going on here?

The with_index method can be called on any iterator object. All it does is pass the index of the element within the array to the block, as a second block argument, in addition to the element itself.

We can then use it inside the block and add the index to the number itself.

For the first iteration, it calls the block with 1 and 0 because 0 is the first position, or index. It returns 1. For the second iteration, it calls the block with 2 and 1 and returns 3, and so on.

The method call eventually returns the array [1, 3, 5, 7, 9].

Remember: Iterators in Ruby are chainable.