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

我想平均与每个产品的哈希键相关的所有评论的分数。我怎样才能做到这一点?

4

3 回答 3

10

遍历哈希:

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
于 2012-11-03T03:18:12.037 回答
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
于 2012-11-03T03:31:18.600 回答
1

感谢新月的回答,我一定会赞成的。我不小心自己想出了答案。

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]}
于 2012-11-03T03:31:27.570 回答