如何计算哈希数组中的值

use*_*830 2 ruby arrays hash

我有一系列哈希

[ {:name => "bob", :type => "some", :product => "apples"},
  {:name => "ted", :type => "other", :product => "apples"},.... 
  {:name => "Will", :type => "none", :product => "oranges"} ]
Run Code Online (Sandbox Code Playgroud)

并且想知道是否有一种简单的方法来计算产品的数量并存储计数以及数组或散列中的值.

我希望结果如下:

@products =  [{"apples" => 2, "oranges => 1", ...}]
Run Code Online (Sandbox Code Playgroud)

Aru*_*hit 6

你可以这样做

array = [
  {:name => "bob", :type => "some", :product => "apples"},
  {:name => "ted", :type => "other", :product => "apples"},
  {:name => "Will", :type => "none", :product => "oranges"} 
]

array.each_with_object(Hash.new(0)) { |h1, h2| h2[h1[:product]] += 1 }
# => {"apples"=>2, "oranges"=>1}
Run Code Online (Sandbox Code Playgroud)