how to sum hash values in an array of five hashes? in ruby

To sum the hash values in an array of five hashes in Ruby, you can iterate over each hash and accumulate the values using the Enumerable#reduce method.

Here's an example:

main.rb
array_of_hashes = [
  { key1: 10, key2: 20, key3: 30 },
  { key1: 40, key2: 50, key3: 60 },
  { key1: 70, key2: 80, key3: 90 },
  { key1: 100, key2: 110, key3: 120 },
  { key1: 130, key2: 140, key3: 150 }
]

sum = array_of_hashes.reduce(Hash.new(0)) do |result, hash|
  hash.each do |key, value|
    result[key] += value
  end
  result
end

puts sum
350 chars
17 lines

In this example, we have an array array_of_hashes containing five hashes. We initialize the sum variable as a new empty hash with default values of 0.

Then, we use reduce to iterate over each hash in the array. For each hash, we iterate over its key-value pairs and add the value to the respective key in the sum hash. Finally, we output the sum hash.

The result will be a hash with the sum of all the corresponding values from each hash in the array:

main.rb
{ :key1 => 350, :key2 => 400, :key3 => 450 }
45 chars
2 lines

related categories

gistlibby LogSnag