DEV Community

Cindy
Cindy

Posted on

Ruby Enumerable

The Ruby Enumerable module is an amazing tool. It provides many ways (methods) to go over every element in an array and do something to the elements or grab certain elements from the array. There are many methods, but I am going to go over a few that I use often.

select method

Array#select (# denotes a method) will go through every element in the array and pick out the elements that satisfies the condition that is inside the block, which starts and ends with a curly brace ({}) plus anything inside the curly braces. These elements are then put into a new array and the new array is returned. The elements that do not satisfy the condition are not included in the new array.

Alt Text

The word in between the | | (“pipe” character) represents one element. You can call it whatever you like, but I usually like to call it based on what is in the array. In the example, we had an array of numbers, so I used the word “number”. I like to keep the word singular to remind myself that it represents one element. If we had an array of names, I would use |name|.

Alt Text

There are two ways you can write the block. One using curly braces, one using do…end. If the block is going to be just one line, use curly braces. If the block is going to be multiple lines, use do…end. In the example, I used do…end for a block that usually can be done in a one line, which works, but the code looks better and more concise if you use curly braces when you can.

map / collect method

Array#map and Array#collect have the same function. They will go through every element in the array and do “something” to every element. That “something” / action will be written inside the block. For this method, you will have an action inside rather than a condition like we did for the select method. These newly modified elements are then put into a new array and the new array is returned.

Alt Text

Alt Text

find method

Array#find will go through every element in the array until it finds the first element that satisfies the condition. That element is returned and the looping / iterating will end.

Alt Text

If there are no elements that satisfy the condition, nil will be returned.

Top comments (0)