To sum the hash values in an array of five hashes in Ruby, you can iterate over each hash and accumulate the values using the Enumerable#reduce
method.
Here's an example:
main.rb350 chars17 lines
In this example, we have an array array_of_hashes
containing five hashes. We initialize the sum
variable as a new empty hash with default values of 0.
Then, we use reduce
to iterate over each hash in the array. For each hash, we iterate over its key-value pairs and add the value to the respective key in the sum
hash. Finally, we output the sum
hash.
The result will be a hash with the sum of all the corresponding values from each hash in the array:
main.rb45 chars2 lines
gistlibby LogSnag