Ruby tally: Counting Occurrences in Arrays and Hashes Without Building the Hash Yourself
Sooner or later every Rails app needs a count by something. Orders by status, errors by class, log lines by endpoint. The query that sends you to search is usually some version of “ruby count occurrences in array”, and the answer you find first is often a hand-built hash:
counts = Hash.new(0)
statuses.each { |status| counts[status] += 1 }
That works, and I have written it hundreds of times. But since Ruby 2.7 there is a method that does exactly this, and it is worth knowing what it does, what it does not do, and where it stops being the right tool.
What tally does
Enumerable#tally walks the collection once and returns a hash of each distinct element mapped to the number of times it appeared:
statuses = %w[paid pending paid failed paid pending]
statuses.tally
# => {"paid"=>3, "pending"=>2, "failed"=>1}
Keys appear in the order each value was first seen, which is the same ordering you would get from the manual Hash.new(0) loop. The result is a plain hash with no default value, so asking for a value that never appeared returns nil, not 0:
counts = statuses.tally
counts["refunded"]
# => nil
counts.fetch("refunded", 0)
# => 0
That is the first gotcha. If you are going to do arithmetic on a lookup, use fetch with a default or Hash.new(0).merge(counts). Otherwise you will meet NoMethodError: undefined method '+' for nil the first time a category is missing from the data.
Counting by a derived value
Most of the time you are not counting the elements themselves, you are counting something about them. There is no tally_by in Ruby’s standard library, so you map first and tally the result:
Order = Struct.new(:id, :status, :total)
orders = [
Order.new(1, "paid", 40),
Order.new(2, "pending", 15),
Order.new(3, "paid", 99),
Order.new(4, "failed", 20)
]
orders.map(&:status).tally
# => {"paid"=>2, "pending"=>1, "failed"=>1}
In a Rails app the same idea works on records, but I would push the work into the database when the collection is an ActiveRecord relation:
Order.group(:status).count
# => {"paid"=>2, "pending"=>1, "failed"=>1}
This is the single most common mistake I see with tally in Rails code: Order.all.map(&:status).tally loads every row into memory just to count a column. It gives the same answer as group(:status).count, but one of them issues a single SELECT status, COUNT(*) ... GROUP BY status and the other instantiates every record. Use tally for data that is already in Ruby, such as a parsed JSON payload, a CSV, a log file, or an array you built in a test. Use group.count when the data lives in a table.
Sorting and picking the top results
A tally is rarely the final answer. You usually want the most common items. Since the result is a hash, sort_by returns an array of pairs, and to_h turns it back into a hash if you need one:
words = %w[ruby rails ruby gem ruby rails test]
words.tally.sort_by { |_word, count| -count }
# => [["ruby", 3], ["rails", 2], ["gem", 1], ["test", 1]]
words.tally.max_by { |_word, count| count }
# => ["ruby", 3]
words.tally.sort_by { |_word, count| -count }.first(2).to_h
# => {"ruby"=>3, "rails"=>2}
Notice that gem and test are tied. sort_by is not stable in Ruby, so ties can come out in either order. If the output is user-facing or compared in a test, add a tiebreaker:
words.tally.sort_by { |word, count| [-count, word] }
# => [["ruby", 3], ["rails", 2], ["gem", 1], ["test", 1]]
Sorting by an array works because arrays compare element by element. It is a small habit that removes a whole class of flaky tests.
Accumulating across batches
Since Ruby 3.1, tally accepts a hash to add to. That lets you count in chunks without merging by hand:
totals = {}
%w[a b a].tally(totals)
%w[b c].tally(totals)
totals
# => {"a"=>2, "b"=>2, "c"=>1}
This mutates the hash you pass in and returns it. It is handy when you are streaming a large file line by line with each_slice and do not want to hold everything in memory. Be careful that the hash you pass in has only integer values. If it holds anything else, tally raises a TypeError, and a frozen hash raises FrozenError. That is a reasonable failure, and I would rather have it than a silent miscount.
tally versus group_by versus sum
These three get confused, so here is how I choose.
Use tally when you only need counts. It is the clearest expression of intent and it does not keep the elements around.
Use group_by when you need the elements themselves, not just how many there are:
orders.group_by(&:status).transform_values(&:count)
# => {"paid"=>2, "pending"=>1, "failed"=>1}
That produces the same counts as orders.map(&:status).tally, but it builds arrays of full orders on the way. If counts are all you need, you are paying for memory you do not use. If you also want the totals per status, though, group_by is the better start:
orders.group_by(&:status).transform_values { |group| group.sum(&:total) }
# => {"paid"=>139, "pending"=>15, "failed"=>20}
Use sum with a block when you are adding a number rather than counting occurrences. A tally is a sum of ones, and as soon as the number you add stops being one, you have outgrown it.
For anything that needs more than one aggregate at a time, such as count, sum, and average per status, I reach for each_with_object and build the hash explicitly. I wrote about when that beats reduce in a separate post, and the same reasoning applies here: once the loop body does real work, a named accumulator is easier to read than a chain of clever one-liners.
Using tally in tests
Counting is a good way to assert on collections whose order you do not control. If a query returns records in an unspecified order, comparing the arrays directly is brittle. Comparing their tallies is not:
expected = %w[paid paid pending]
actual = Order.where(account: account).pluck(:status)
assert_equal expected.tally, actual.tally
This checks that the same values appear the same number of times, ignoring order, and the failure message shows two small hashes instead of two long arrays. It is a stricter check than assert_equal expected.sort, actual.sort only in that it tells you which value is off, and on a failure that is what you actually want to read.
A short checklist
Reach for tally when the data is already in Ruby and you want counts. Remember it returns nil for missing keys, so use fetch when you do arithmetic on a lookup. Sort with a tiebreaker. Keep group(:column).count for ActiveRecord relations so the database does the counting. And when you start wanting more than a count, switch to group_by or each_with_object rather than stretching tally past what it was designed for.
Comparing two hashes of counts, or a tally that does not match what you expected? Try RubyHash, a free in-browser hash diff viewer. Nothing is uploaded, everything runs in your browser.
Enjoyed this post?
Subscribe to get notified when we publish more Ruby and Rails content.