如何计算哈希数组中的值

时间:2014-07-25 03:32:22

标签: ruby arrays hash

我有一系列哈希

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

并且想知道是否有一种简单的方法可以计算产品的数量并将数量和值存储在数组或散列中。

我希望结果如下:

@products =  [{"apples" => 2, "oranges => 1", ...}]

5 个答案:

答案 0 :(得分:5)

你可以这样做

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}

答案 1 :(得分:2)

您可以使用Enumerable#group_byEnumerable#map

array.group_by{|h| h[:product]}.map{|k,v| [k, v.size]}.to_h
# => {"apples"=>2, "oranges"=>1}

答案 2 :(得分:0)

你可以算一下:

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

hashes.inject(Hash.new(0)) { |h,o| h[o[:product]] += 1; h }

或者也许......

hashes.instance_eval { Hash[keys.map { |k| [k,count(k)] }] }

我不知道哪个性能更高,后者看起来很奇怪。

答案 3 :(得分:0)

我愿意:

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

 counts = items.group_by{|x|x[:product]}.map{|x,y|[x,y.count]}
 p counts #=> [["apples", 2], ["oranges", 1]]

然后,如果你需要它作为哈希只是做:

 Hash[counts]

答案 4 :(得分:0)

虽然不是OP正在寻找的东西,但这可能对许多人有所帮助。如果您只是在寻找特定产品的数量,您可以这样做:

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

array.count { |h| h[:product] == 'apples' }
# => 2