Array#tally

Added in v3.0 · Updated March 13, 2026 · Array Methods
ruby array tally

The .tally method counts how many times each element appears in an array. It returns a hash where keys are the unique elements and values are their occurrence counts.

This method was introduced in Ruby 2.7 as an Enumerable method and became available on Array in Ruby 3.0. The optional hash parameter was added in Ruby 3.1.

Syntax

arr.tally -> hash
arr.tally(hash) -> hash (Ruby 3.1+)

.tally takes no required parameters. In Ruby 3.1+, you can pass an existing hash to accumulate counts into.

Parameters

ParameterTypeDefaultDescription
hashHashnilOptional (Ruby 3.1+). A hash to accumulate counts into.

Examples

Basic string counting

fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]
fruits.tally
# => {"apple"=>3, "banana"=>2, "orange"=>1}

Counting integers

scores = [95, 87, 95, 92, 87, 90, 95]
scores.tally
# => {95=>3, 87=>2, 92=>1, 90=>1}

Using with a block (Ruby 3.0+)

words = ["hello", "world", "HELLO", "ruby", "WORLD"]
words.tally(&:upcase)
# => {"HELLO"=>2, "WORLD"=>2, "RUBY"=>1}

Using hash accumulator (Ruby 3.1+)

existing_counts = { "ruby" => 5 }
["ruby", "python", "ruby"].tally(existing_counts)
# => {"ruby"=>7, "python"=>1}

Common Use Cases

Finding the most frequent element

votes = ["Alice", "Bob", "Alice", "Charlie", "Alice", "Bob"]
tally = votes.tally
most_voted = tally.max_by { |_, count| count }
# => ["Alice", 3]

Filtering by frequency

letters = ["a", "b", "a", "c", "a", "b", "d"]
letters.tally.select { |_, count| count > 1 }
# => {"a"=>3, "b"=>2}

Performance

.tally has O(n) time complexity since it iterates through the array once. It builds a hash internally, so space complexity is O(u) where u is the number of unique elements.

This is significantly faster than the manual approach using .each_with_object(Hash.new(0)):

# Slower manual approach
arr.each_with_object(Hash.new(0)) { |k, h| h[k] += 1 }

# Faster native method
arr.tally

See Also

  • arr-count — Count elements matching a condition or value
  • arr-uniq — Return unique elements from an array
  • arr-filter — Select elements matching a condition