How to build a frequency tally from an array
A frequency tally is useful for tags, statuses, words, or any repeated values in a list. This recipe shows a compact way to count repeated values while keeping the loop easy to read and easy to adapt for another kind of 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. That keeps the tally logic focused on the data and makes it easy to reuse for words, tags, statuses, or quick reports. If you need ordering or presentation later, handle that as a separate step so the counting code stays short and clear. Related references are Hash and Enumerable.
sorted = counts.sort_by { |item, total| [-total, item] }
puts sorted
# [["red", 3], ["blue", 2], ["green", 1]]
That extra step is useful when the tally needs to be displayed or compared. Counting stays simple, and the sort happens after the frequencies are known, which keeps the recipe easy to adapt for reports or small summaries. If you later need a different order, the counting loop does not have to change at all.