The secrets of ruby enumerable

Merce Bauza
2 min readDec 5, 2018

--

Coming from a Java background, learning ruby has its challenges.

I tend to write all the methods using loops and temporary variables and booleans… and there’s nothing wrong with it, but I always end up with very long and clunky and sometimes complex methods, that they could be difficult to read or to understand.

In ruby, fortunately, the enumerable module has helped me (and make my life easier) when writing methods, because it has an enormous list of helper methods, specially for sorting, selecting, finding… that I could use instead of writing all the functionality myself, and the resulting code even looked simpler and shorter.

For instance, imagine that I have an array of players of a game and I want to know if someone has won by checking all the players of my array and calling the function is_a_winner(player) on each one.

In order to do that, I need to loop through all my players and for each player I need call the “is_a_winner(player)”, return true if he/she is a winner or false if none of them are.

Following that logic, I came up with this method.

def won?(players)    
for player in players do
return true if is_a_winner?(player)
end
false
end

Not too bad, but what if there is one helper method that could do all that?

Checking the enumerable module, I found that “.any?” could do exactly the same but avoiding booleans, loops and in a single line.

It checks if any of players is_a_winner. It is even simpler to understand.

def has_a_winner?(players)    
players.any? { |player| is_a_winner?(player) }
end

This is only one example of all the helper methods that I could use instead of writing all the functionality myself.

I have found myself using the Enumerable methods in every class and it has simplified my methods and also speed up my productivity.

The challenge here is to find the right one to use, but over time it will become easier. And for now, there are plenty of examples out there to check out!

--

--

Merce Bauza
Merce Bauza

Written by Merce Bauza

Software crafter at 8th light

No responses yet