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.rb108 chars5 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
gistlibby LogSnag