我有一个哈希数组
[ {:name => "bob", :type => "some", :product => "apples"},
{:name => "ted", :type => "other", :product => "apples"},....
{:name => "Will", :type => "none", :product => "oranges"} ]
并且想知道是否有一种简单的方法来计算产品的数量并将计数以及值存储在数组或哈希中。
我希望结果是这样的:
@products = [{"apples" => 2, "oranges => 1", ...}]
最佳答案
你可以这样做
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}
关于ruby - 如何计算哈希数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24947589/