Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over hash of arrays

Tags:

ruby

I have the following:

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

I want to average the scores for all reviews associated with each product's hash key. How can I do this?

like image 812
Abram Avatar asked Dec 17 '25 07:12

Abram


1 Answers

To iterate over a hash:

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

To iterate over an array:

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

So iterating over a hash of arrays (let's say we're iterating over each array in each point in the hash) would be done like so:

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!