How to build a frequency tally from an array

· 1 min read · Updated March 12, 2026 · beginner
ruby arrays hash enumeration

A frequency tally is useful for tags, statuses, words, or any repeated values in a list.

Recipe

items = ["red", "blue", "red", "green", "blue", "red"]

counts = items.each_with_object(Hash.new(0)) do |item, tally|
  tally[item] += 1
end

puts counts
# {"red"=>3, "blue"=>2, "green"=>1}

The Hash.new(0) default is the important part: missing keys start at zero, so incrementing stays simple. This pattern is handy for words, tags, statuses, and lightweight reporting.

See Also