Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby "count" method for hashes

Tags:

ruby

I have a hash in which I want to use the values as keys in a new Hash which contains a count of how many times that item appeared as a value in the original hash.

So I use:

hashA.keys.each do |i|
    puts hashA[i]
end

Example output:

0
1
1
2
0
1
1

And I want the new Hash to be the following:

{ 0 => 2,  1 => 4,  2 => 1 }
like image 760
Derek Avatar asked Oct 24 '11 00:10

Derek


1 Answers

counts = hashA.values.inject(Hash.new(0)) do |collection, value|
  collection[value] +=1
  collection
end
like image 98
Brian Rose Avatar answered Nov 12 '22 12:11

Brian Rose