Tally-me Bananas! Understanding How Ruby’s New Tally Method Works

Laurence Hawelu
2 min readApr 8, 2021

Recently I was given the task of returning the count of specific values in an array. As I went through my Google search results I came across a newer method (Ruby 2.7+) called Tally. Tally reviews an array and returns the count of each element. The return value will be a hash where the key is the element and the value is the total number of occurrences in the array.

To better understand what Tally is doing we will go through the example code below:

Let’s run through this piece by piece:

Step 1 — Iterate over each element in the array passing the element and the memo

Step 2 — Create new hash with default value set to zero

Step 3 — As element and memo are received, check to see if hash is present. If it is present add one to the count and if not create a new hash and start the count as one

Below is is the whole block of code to display how to use the above example and what the return value will be:

With Tally you can quickly do this, and it is more readable to others since they can easily identify the method name:

As you can see from the example above the Tally method has provided a clean, concise way to create a hash that identifies the total number of times an element is present in an array. I hope this method helps you as much as it did for me!

--

--