Ruby 2.7 adds Enumerable#tally . Tally returns a new hash where the keys are the elements and the values are numbers of elements in the collection that correspond to the key.
Lets say we want to create a new hash that contains the counts of elements in an array. We can achieve this by doing something so:
As you can see, we need to jump some hoops here for a simple task. We need to first group elements and then proceed to create a new hash out of the array.
We can now use
Enumerable#tally in Ruby 2.7 to to achieve this in a simpler way:
As you see, tally creates a new hash with keys as unique elements, and sets values as the count of occurrences of every element.
This comes in pretty handy for creating lists with their element counts for display or other purposes.
You can read more about the development of the feature here.
We might see the ability to pass blocks in future to
to compute keys as well, used to count occurrences.