Derek
Derek

Reputation: 9943

Ruby "count" method for hashes

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 }

Upvotes: 8

Views: 8692

Answers (2)

Dave Newton
Dave Newton

Reputation: 160170

TL;DR: 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} 

Upvotes: 7

Brian Rose
Brian Rose

Reputation: 1725

counts = hashA.values.inject(Hash.new(0)) do |collection, value|
  collection[value] +=1
  collection
end

Upvotes: 17

Related Questions