Array#tally
Updated March 31, 2026 · Array Methods
ruby array tally count stdlib
Array#tally
Counts occurrences of each element in the array and returns a hash where keys are elements and values are their respective counts.
Basic Usage
fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]
fruits.tally
# => {"apple"=>3, "banana"=>2, "orange"=>1}
With a Block
You can pass a block to tally to count based on the block’s return value:
words = ["hello", "world", "ruby", "hello", "world", "world"]
words.tally { |word| word.length }
# => {5=>2, 6=>1, 4=>3}
This counts how many words have each length.
Tally vs Count
These methods are related but serve different purposes:
countcounts elements that match a given condition and returns an integertallycounts all elements and returns a hash
numbers = [1, 2, 2, 3, 3, 3]
# count - how many elements equal 2?
numbers.count(2)
# => 2
# tally - how many of each element?
numbers.tally
# => {1=>1, 2=>2, 3=>3}
Tally vs Group By
Both return hashes but with different values:
group_bygroups elements into arraystallygroups elements into integer counts
words = ["hello", "world", "ruby", "hello"]
# group_by - elements grouped into arrays
words.group_by(&:itself)
# => {"hello"=>["hello", "hello"], "world"=>["world"], "ruby"=>["ruby"]}
# tally - elements counted into integers
words.tally
# => {"hello"=>2, "world"=>1, "ruby"=>1}
Practical Examples
Word Frequency
Count how often each word appears in a text:
text = "the quick brown fox jumps over the lazy dog the fox"
text.split.tally
# => {"the"=>2, "quick"=>1, "brown"=>1, "fox"=>2, "jumps"=>1, "over"=>1, "lazy"=>1, "dog"=>1}
Vote Counting
votes = ["Alice", "Bob", "Alice", "Charlie", "Bob", "Alice", "Bob", "Bob"]
votes.tally
# => {"Alice"=>3, "Bob"=>4, "Charlie"=>1}
winner = votes.tally.max_by { |name, count| count }
# => ["Bob", 4]
Inventory Count
inventory = ["sword", "potion", "shield", "sword", "sword", "potion", "ring"]
inventory.tally
# => {"sword"=>3, "potion"=>2, "shield"=>1, "ring"=>1}
Character Occurrences
"hello world".chars.tally
# => {"h"=>1, "e"=>1, "l"=>3, "o"=>2, " "=>1, "w"=>1, "r"=>1, "d"=>1}
Performance
Array#tally has O(n) time complexity, where n is the number of elements in the array. It makes a single pass through the array, updating a hash counter for each element.
See Also
- /reference/enumerable/enumerable-tally/ — The Enumerable version that works with any enumerable
- /reference/array-methods/array-uniq/ — Get unique elements from an array
- /reference/enumerable/enumerable-group-by/ — Group elements into arrays by a criteria