Ruby 2.7 adds Enumerable#tally

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.


Let’s 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:

array = [9, 19, 11, 11, 11]
# => {9=>1, 19=>1, 11=>3}

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 achieve this in a simpler way:

# There are 3 occurrences of element 11,
# and single of other elements
[9, 19, 11, 11, 11].tally
# => {9=>1, 19=>1, 11=>3}  

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.

cars_at_party = %w{Volvo BMW Toyota Volvo Toyota Toyota}
#=> {"Volvo"=>2, "BMW"=>1, "Toyota"=>3}
nationalities_of_conference_attendees = %w{Japan USA USA India India China}
#=> {"Japan"=>1, "USA"=>2, "India"=>2, "China"=>1}


You can read more about the development of the feature here. We might see the ability to pass blocks in future to tally_by, to compute keys as well, used to count occurrences.