Ruby 2.7 introduced the
Enumberable#tally method. It allows to easily count elements’ occurrences in a given collection. In other words, it literally tallies them up. :)
The use case
Say we have a collection of words, and we’d like to count the occurrences of each word within it.
Pre Ruby 2.7
In previous versions of Ruby, whenever we encountered a logic counting occurrences of collection elements (here: words in the array), we would most likely see a code similar to this:
This could be simplified by initializing the Hash with a default value of
0 (which makes total sense in this case):
We could even transform it further to a one-liner using
I personally like the second solution the most. I think it strikes the best balance between simplicity and ease of understanding.
As we can see, all of the above approaches rely on iterating through the collection to tally up its members.
There is also another approach that could be chosen: relying on
Enumerable#group_by. If I were to use this one, the code I would write would probably look something like this:
The new way
Since Ruby 2.7, we could get the same result (a Hash containing numbers of occurrences of each element) by simply invoking the
#tally method on the collection.
It’s not only a nice shortcut, it also expresses the intent in a clear way - something many of us love in Ruby code.
Have you had a chance to use the
Enumerable#tally method in your production code yet? Please share in the comments below!
Do you use continuous integration in your Ruby project? Consider using Knapsack Pro to increase your team’s productivity by shortening build times on your CI server!