how to compute the sum in [{:l=>8},{:s=>7, :m=>2}]? in ruby

To compute the sum of the values in the provided array of hashes in Ruby, you can use the reduce method. Here's an example:

main.rb
array = [{:l=>8}, {:s=>7, :m=>2}]
sum = array.reduce(0) { |total, hash| total + hash.values.sum }

puts sum
108 chars
5 lines

The reduce method is used to iterate over each hash in the array and sum the values for each hash. hash.values returns an array of the values of the hash, and sum is used to calculate the sum of those values. The initial value passed to reduce is 0.

In this example, the sum will be 17, which is the sum of 8+7+2.

Tags: ruby, sum, hash, array

related categories

gistlibby LogSnag