DEV Community

Mel Kaulfuss
Mel Kaulfuss

Posted on

Enumerable#tally in Ruby 2.7

The tally method has been added to Enumerable in Ruby 2.7

It's a simple little method and as the name suggests, it tallys things for us! It affords us a much simpler way to group items and count their occurrence.

We could always count the size of an array.

fruit_bowl = ["apple", "pear", "pear", "banana", "apple"]

fruit_bowl.count 
=> 4
Enter fullscreen mode Exit fullscreen mode

We could count how many of each item an array contained.

fruit_bowl.each.count("apple") 
=> 2
Enter fullscreen mode Exit fullscreen mode

Now we can easily take stock of our array items with tally which will return us a list of items with their respective counts.

fruit_bowl = ["apple", "pear", "pear", "banana", "apple"]

sorted_fruit = fruit_bowl.tally
=> {"apple"=>2, "pear"=>2, "banana"=>1}

sorted_fruit["apple"]
=> 2
Enter fullscreen mode Exit fullscreen mode

Sweet as πŸ“πŸ˜‹

Top comments (1)

Collapse
 
anicholson profile image
Andy Nicholson

Love it! I was hacking on a project in Rust the other day and wanted something just like #tally! It felt fiddly to write myself and I kept thinking β€œthis is such a breeze in Ruby” ❀️