迭代数组的哈希值

Abr*_*ram 2 ruby

我有以下内容:

@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>
  ]
}
Run Code Online (Sandbox Code Playgroud)

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

小智 10

迭代哈希:

hash = {}
hash.each_pair do |key,value|
  #code
end
Run Code Online (Sandbox Code Playgroud)

迭代数组:

arr=[]
arr.each do |x|
  #code
end
Run Code Online (Sandbox Code Playgroud)

因此,遍历数组的散列(假设我们在散列中的每个点上迭代每个数组)将如下所示:

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
Run Code Online (Sandbox Code Playgroud)


Aar*_*ley 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
Run Code Online (Sandbox Code Playgroud)