Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#tally

enum.tally → a_hash

Tallies the collection, i.e., counts the occurrences of each element. Returns a hash with the elements of the collection as keys and the corresponding counts as values.

Example
["a", "b", "c", "b"].tally  #=> {"a"=>1, "b"=>2, "c"=>1}
See also #take_while #to_a #take #to_h also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1