简体   繁体   中英

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 }
counts = hashA.values.inject(Hash.new(0)) do |collection, value|
  collection[value] +=1
  collection
end

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} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM