用于散列的Ruby"count"方法

Der*_*rek 8 ruby

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

所以我使用:

hashA.keys.each do |i|
    puts hashA[i]
end
Run Code Online (Sandbox Code Playgroud)

示例输出:

0
1
1
2
0
1
1
Run Code Online (Sandbox Code Playgroud)

我希望新的Hash如下:

{ 0 => 2,  1 => 4,  2 => 1 }
Run Code Online (Sandbox Code Playgroud)

小智 17

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

  • +1表示块中有意义的变量名称; 我忘记了当你不了解API时,它们很重要. (5认同)

Dav*_*ton 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} 
Run Code Online (Sandbox Code Playgroud)