2012-11-03 179 views
2

的哈希我有以下幾點:遍歷數組

@products = { 
    2 => [ 
    #<Review id: 9, answer01: 3, score: 67, style_id: 2, consumer_id: 2, 
    branch_id: 2, business_id: 2> 
    ], 
    15 => [ 
    #<Review id: 10, answer01: 3, score: 67, style_id: 2, consumer_id: 2, 
    branch_id: 2, business_id: 2>, 
    #<Review id: 11, answer01: 3, score: 67, style_id: 2, consumer_id: 2, 
    branch_id: 2, business_id: 2> 
    ] 
} 

我要平均每個產品的散列鍵相關聯的所有評論的分數。我怎樣才能做到這一點?

+2

請添加解決方案作爲答案並接受它。 – Mischa

+0

我知道,你必須等一會兒纔可以。請儘可能接受它。或者,如果你想要很好接受Aaron Perley的回答;-) – Mischa

+1

完成。謝謝Aaron – Abram

回答

6

是的,只需使用map來製作一個每個產品的分數的數組,然後取數組的平均值。

average_scores = {} 
@products.each_pair do |key, product| 
    scores = product.map{ |p| p.score } 
    sum = scores.inject(:+) # If you are using rails, you can also use scores.sum 
    average = sum.to_f/scores.size 
    average_scores[key] = average 
end 
9

要遍歷一個哈希:

hash = {} 
hash.each_pair do |key,value| 
    #code 
end 

遍歷數組:

arr=[] 
arr.each do |x| 
    #code 
end 

所以在陣列的哈希迭代(假設我們正在迭代中的每個點每個陣列在散列中)將如下完成:

hash = {} 
hash.each_pair do |key,val| 
    hash[key].each do |x| 
    #your code, for example adding into count and total inside program scope 
    end 
end 
1

感謝您的回答Shingetsu,我肯定會讚揚它。我無意中想出了自己的答案。

trimmed_hash = @products.sort.map{|k, v| [k, v.map{|a| a.score}]} 
trimmed_hash.map{|k, v| [k, v.inject(:+).to_f/v.length]}