用于哈希的Ruby“count”方法

时间:2011-10-24 00:55:50

标签: ruby

我有一个哈希,我希望在新哈希中使用这些值作为键,其中包含该项目在原始哈希值中出现的次数的计数。

所以我用:

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

示例输出:

0
1
1
2
0
1
1

我希望新的Hash如下:

{ 0 => 2,  1 => 4,  2 => 1 }

2 个答案:

答案 0 :(得分:17)

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

答案 1 :(得分:7)

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}