There’s more than just .each!?

Isaac Avilez
3 min readFeb 2, 2020

--

You heard it here! When I was first introduced to Ruby and it’s enumerables, I struggled, a lot. I had a hard time grasping what to do with these enumerables that were provided to us, and I know that I wasn’t the only one struggling with such methods. I’m also here to inform you about the many other enumerables that can make your life much easier! Such as: .map, .select, .find, and much more, but lets start you off with the basics first! If we remember correctly, .each iterates over each element in the array, but it also returns the original array.

Here’s an example of .each in use:

.each adding one to each element on the array
What is returned in the console after the block of code is ran.

As we see above, after the block of code is ran, it adds 1 to each element to the array, and then returns the original, but what would happen if we’d like to alter the array? No worries, .map is here for us!

Here’s an example of .map in use:

.map adding one to each element of the array.
What’s returned after the block of code is ran.

As we can see, the difference between .map and .each is that both will iterate over the array, and run the block of code on each element, but .map will return a new array, as opposed to .each which will return the original array.

Here’s an example of .select in use:

.select iterating over the array and executing the block of code.
What’s returned after the block of code is ran.

As we can see, the main difference between .map/.each and .select is that .select will iterate over the array, and will return a new array with everything that evaluated to true in the block of code that was ran. You can sort of think of .select being used as a filter.

Here’s an example of .find being used:

.find enumerable being used.
What’s returned after the block of code is ran.

Finally, we’re at our last enumerable that could make life for us much more simpler than having to run .each on every type of iteration. The .find enumerable returns the FIRST for which evaluates to true in the block of code.

There are many more enumerables that we can use in ruby, but for now, the way I started to enhance my skills and move away from constantly using .each, I used these enumerables provided above to make our code much shorter, better to read for other programmers, and will also benefit us more in the future.

--

--

No responses yet