How can I convert an array to a hash that reflects the number of times each unique element in the array appears in the array?

100 views Asked by At

Given an array I would like to create a hash whose keys are the unique elements of the array and whose values are the numbers of times the corresponding key appears in the array.

For example, if the array were

["americans", "oath", "oath", "generation", "americans"]

the associated hash would be

{ "americans"=>2, "oath"=>2, "generation"=>1 }
1

There are 1 answers

2
spickermann On

There is the Enumerable#tally method that does exactly that:

["americans", "oath", "oath", "generation", "americans"].tally
#=> { "americans" => 2, "oath" => 2, "generation" => 1 }