我有以下内容:
@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>
]
}
我想平均与每个产品的哈希键相关的所有评论的分数。我怎么能这样做?
答案 0 :(得分: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 :(得分: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
答案 2 :(得分: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]}