how to compute the total found in this array? [{:s=>3, :m=>7, :l=>8},{:s=>7, :m=>2}] in ruby

To compute the total found in the given array, you can use the reduce method in Ruby. Here's an example code snippet:

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

This code will output the total sum of all the values in the array, which in this case is 27.

In the reduce method, we start with an initial value of 0 and then iterate over each hash element in the array. For each hash, we calculate the sum of its values using the values method, and add it to the running sum. Finally, the total sum is printed.

Note: If the array contains non-integer values, you might need to handle those separately.

related categories

gistlibby LogSnag