Ruby 2.7 introduced a small but powerful method: tally
. If you’ve ever written code to count how many times each item appears in a collection, you’re going to love this.
What Is tally
?
The tally
method is available on any object that includes Enumerable
, like arrays. It returns a hash where the keys are the unique elements from the collection, and the values are the number of times each element appears.
A Basic Example
Here’s how you’d use tally
in a typical scenario:
1
2
["apple", "banana", "apple", "orange", "banana", "apple"].tally
# => {"apple"=>3, "banana"=>2, "orange"=>1}
No loops, no manual hashes — just one clean, readable line.
Without tally
: The Old Way
Before tally
, counting occurrences looked more like this:
1
2
3
4
5
counts = Hash.new(0)
["apple", "banana", "apple"].each do |fruit|
counts[fruit] += 1
end
# => {"apple"=>2, "banana"=>1}
It works fine, but tally
makes this common pattern much more concise.
Use Cases for tally
Here are a few situations where tally
shines:
Counting votes
1
2
3
votes = ["yes", "no", "yes", "yes", "no"]
votes.tally
# => {"yes"=>3, "no"=>2}
Word frequencies
1
2
3
4
sentence = "the quick brown fox jumps over the lazy dog"
words = sentence.split
words.tally
# => {"the"=>2, "quick"=>1, "brown"=>1, ...}
Grouping errors or statuses
1
2
3
statuses = [:ok, :ok, :error, :timeout, :ok, :error]
statuses.tally
# => {:ok=>3, :error=>2, :timeout=>1}
Things to Keep in Mind
tally
works only onEnumerable
s (like arrays). It doesn’t exist for plain hashes.- It returns a new hash; the original array is unchanged.
- If you need weighted tallies or conditional logic, you might still need custom logic — but for simple counts,
tally
is perfect.
Ruby’s tally
method is a great example of how the language evolves to make code more expressive and elegant. It replaces a common multi-line pattern with a single readable line, and once you start using it, you’ll likely reach for it often.