how to return the total value, as an integer, of all the hash values of three hashes, each of which is an element of an array? in ruby

To return the total value of all the hash values of three hashes, each of which is an element of an array, you can do the following in Ruby:

main.rb
# Create an array with three hashes
hashes_array = [
  { key1: 10, key2: 20, key3: 30 },
  { key4: 40, key5: 50, key6: 60 },
  { key7: 70, key8: 80, key9: 90 }
]

# Initialize a variable to hold the total value
total_value = 0

# Iterate over each hash in the array
hashes_array.each do |hash|
  # Iterate over each value in the hash and add it to the total value
  hash.each_value do |value|
    total_value += value
  end
end

# Output the total value
puts total_value
471 chars
21 lines

This code will iterate over each hash in the hashes_array, and then iterate over each value in each hash, adding it to the total_value. Finally, the code will output the total_value.

Note: This assumes that the hash values are integers. If they can be of different data types, you may need to add additional checks or type conversions.

related categories

gistlibby LogSnag