how to return the total value of all the hash values of three hashes, each of which is an element of an array using map or some shorter code? in ruby

You can use the map method along with the inject method to achieve this. Here's how you can do it:

main.rb
array_of_hashes = [{a: 1, b: 2}, {c: 3, d: 4}, {e: 5, f: 6}]

total_value = array_of_hashes.map { |hash| hash.values }.flatten.inject(0, :+)

puts total_value
# Output: 21
172 chars
7 lines

In the above code, we use the map method to iterate over each hash in the array and retrieve all the values using the values method. This gives us an array of arrays. To transform the array of arrays into a single flat array, we use the flatten method.

Finally, we call the inject method on the flattened array with an initial value of 0 and the :+ symbol as an argument to perform the addition operation. This gives us the total value of all the hash values.

Note: I assumed that you wanted to sum up all the values in the hashes. If you have different requirements for calculating the total, please let me know.

related categories

gistlibby LogSnag