Ruby Counting Method for Hashes

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

Therefore, I use:

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

Output Example:

 0 1 1 2 0 1 1 

And I want the new hash to be as follows:

 { 0 => 2, 1 => 4, 2 => 1 } 
+8
ruby
source share
2 answers
 counts = hashA.values.inject(Hash.new(0)) do |collection, value| collection[value] +=1 collection end 
+17
source share

TL DR: hashA.values.inject(Hash.new(0)) { |m, n| m[n] += 1; m } hashA.values.inject(Hash.new(0)) { |m, n| m[n] += 1; m }

 > hashA = { a: 0, b: 1, c: 1, d: 2, e: 0, f: 1, g: 1 } => {:a=>0, :b=>1, :c=>1, :d=>2, :e=>0, :f=>1, :g=>1} > hashCounts = hashA.values.inject(Hash.new(0)) { |m, n| m[n] += 1; m } => {0=>2, 1=>4, 2=>1} 
+7
source share

All Articles