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.

Before

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]
Hash[array.group_by{|x|x}.map{|x,y|[x,y.size]}]
# => {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.

Enumerable#tally

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}
cars_at_party.tally
#=> {"Volvo"=>2, "BMW"=>1, "Toyota"=>3}
nationalities_of_conference_attendees = %w{Japan USA USA India India China}
nationalities_of_conference_attendees.tally
#=> {"Japan"=>1, "USA"=>2, "India"=>2, "China"=>1}

Future

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.

Need help on your Ruby on Rails or React project?

Join Our Newsletter