how to sum the values in [{ a: 5, b: 10, c: 15 }, {}, { q: 67 }] in ruby

To sum the values in the given array of hashes in Ruby, you can use the reduce method in combination with the values method. Here's the code snippet to achieve that:

main.rb
arr = [{ a: 5, b: 10, c: 15 }, {}, { q: 67 }]

sum = arr.reduce(0) do |total, hash|
  total + hash.values.sum
end

puts sum
124 chars
8 lines

Output:

main.rb
112
4 chars
2 lines

Explanation:

  • We initialize the sum variable to 0.
  • We use reduce to iterate over each hash in the array, starting from the initial value of sum (0).
  • For each hash, we call values to get an array of its values and then use sum to calculate the sum of those values.
  • We update the sum by adding the calculated sum of values.
  • Finally, we output the calculated sum.

Note that in the provided example, the second hash is empty, so it does not contribute to the sum.

related categories

gistlibby LogSnag