Scott Watermasysk Husband, Father, and KickoffLabs co-founder. Interests: basketball, bootstrapping, keyboards, training, and Building new things

Ruby Enumerable#tally


10+ years in, and Ruby continues to surprise me.

I am trying to complete the Advent of Code this year. For day two, I needed to be able to sum the number of items in an array.

array = ["a", "a", "b"]
# {"a" => 2, "b" => 1}

One of my favorite little Ruby hacks is setting the default value of Hash:

I have done something like this hundreds of times for quick counts:

array = ["a", "a", "b"]
hash =
array.each { |item| hash[item]+=1 }
# {"a" => 2, "b" => 1}

For the Advent of Code, I was curious if there was a good way to do this in one line[1] (no technical reason, just because...)

Not sure why, but it dawned on me this was likely something that Ruby would have built in (again, just because). It turns out in Ruby 2.7, the tally method was added to Enumerable.

Tallies the collection, i.e., counts the occurrences of each element. Returns a hash with the elements of the collection as keys and the corresponding counts as values.

hash = ["a", "a", "b"].tally
# {"a" => 2, "b" => 1}

Simple and named appropriately. Is there another language that would have something like this readily available?

  1. Tap to the rescue - { |h| ["a", "a", "b"].each { |item| h[item]+=1 }} ↩︎