Enumerable Ruby

jordy garcia
2 min readApr 15, 2021

--

Today I want to explain the magic of some enumerable methods in Ruby.

Each method

So for our first enumerable we have one of the most used ones, the “each” method.

The each method will loop over each element in the array, for example if we had an array filled with numbers from one to ten, then it would select each element one by one and let you use that element for solving algorithms.

But how does that work behind the scenes? Does it mean you can solve algorithms without using any loop? The answer is no, as this is a build in method that creates the loop for you using “yield”.

For example:

[1, 2, 3, 4, 5].each { |num| print num if num.even? }

This will print # 2, 4

But how does it actually work? Let me give you an example of how to create this.

So now what is written in yield is actually “num”, as you can see it is just a loop using an index variable to iterate over all your elements.

Each_with_index

The each_with_index is almost similar like the each method. The only difference is that the each_with_index will return you an index as well. So you should also define the index in your block.

For example:

> [“John”, “Doe”, “Susan”, “Diego”].each_with_index do |friend, index| print “#{index + 1}. #{friend}” end

# 1. John

#2. Doe

#3. Susan

#4. Diego

I add “index + 1” as indexes are zero based in ruby and most languages. Let me show you now what is happening behind the scenes, and show you that there is no magic.

As you can see now there are now two arguments in yield, one for selecting the elements and the other one for returning the index.

So now we know that magic is only happening in movies and rails.

--

--

jordy garcia

Full-Stack Web Developer. Ruby on Rails, React, Redux. JavaScript, Improving open-source projects, one commit at a time.