2014-07-25 13 views
1

我有散列如何散列的數組中的計數值

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

的數組,並想知道如果有一個簡單的方法來計算產品的數量和將計以及在價值一個數組或散列。

我想要的結果是這樣的:

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

根據自己的需要,我沒有看到有任何理由將散列保留在Array中。有什麼理由,然後告訴我們。 –

+0

您的預計結果無效。這是不可能的。 – sawa

回答

4

可以作爲

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} 
+0

謝謝你幫助我。我知道有一種方法可以在Ruby中輕鬆完成。我嘗試使用注入,但沒有成功。謝謝:)用於注入的 – user2980830

+1

,試一下'array.inject(Hash.new(0)){| hash,item | hash [item [:product]] + = 1;散列}' – jvnill

+0

@ user2980830閱讀* jvnil的*評論。 –

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)] }] } 

我不知道哪個更高性能,後者雖然可以讀取奇怪的字體。

+0

你可以試試你在IRB中給出的代碼嗎? 'hashes.inject(Hash.new(0)){| h,(_,value)| h [值] + = 1}'這是完全錯誤的。 –

+0

不知道。 – nicooga

+0

我正在嘗試使用注入,因爲我之前用它來計算項目,但從未見過這個「(_,value)」,謝謝你的迴應 – user2980830

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] 
相關問題