how to sum this if the hash is inside an array? [{ a: 5, b: 10, c: 15 }] in ruby

To sum the values of a hash that is inside an array in Ruby, you can use the following code:

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

sum = array.first.values.sum

puts sum
73 chars
6 lines

In this code, we have an array with a single hash { a: 5, b: 10, c: 15 }. We use the .first method to get the first (and only) element of the array. Then, we use .values to retrieve an array of the hash's values. Finally, we use the .sum method to calculate the sum of all the values.

Running this code will output 30 as the sum of the values 5 + 10 + 15.

related categories

gistlibby LogSnag