Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Enumerable#tally

tally → new_hash
tally(hash) → hash

Returns a hash containing the counts of equal elements:

  • Each key is an element of self.

  • Each value is the number elements equal to that key.

With no argument:

Example
%w[a b c b c a c b].tally # => {"a"=>2, "b"=>3, "c"=>3}

With a hash argument, that hash is used for the tally (instead of a new hash), and is returned; this may be useful for accumulating tallies across multiple enumerables:

Example
hash = {}
hash = %w[a c d b c a].tally(hash)
hash # => {"a"=>2, "c"=>2, "d"=>1, "b"=>1}
hash = %w[b a z].tally(hash)
hash # => {"a"=>3, "c"=>2, "d"=>1, "b"=>2, "z"=>1}
hash = %w[b a m].tally(hash)
hash # => {"a"=>4, "c"=>2, "d"=>1, "b"=>3, "z"=>1, "m"=> 1}

Ruby version changes

  1. 3.1
See also #take_while #to_a #take #to_h also in 4.1 · 4.0 · 3.4 · 3.2 · 3.1 · 3.0