how to sum values found in a hash? in ruby

To sum the values found in a hash in Ruby, you can use the #values method to get an array of all the values, and then use the #sum method to calculate the sum.

Here's an example:

main.rb
my_hash = { a: 5, b: 10, c: 15 }

sum = my_hash.values.sum

puts sum # Output: 30
82 chars
6 lines

In this example, my_hash is a hash with keys :a, :b, and :c, and corresponding values 5, 10, and 15. The my_hash.values call retrieves an array [5, 10, 15], and then sum calculates the sum of these values, which is 30.

You can replace my_hash with your actual hash, and adjust the keys and values accordingly.

Note that the #sum method is available from Ruby 2.4 onwards. If you're using an older version of Ruby, you can use the #reduce method instead:

main.rb
sum = my_hash.values.reduce(:+)
32 chars
2 lines

This works in a similar way to #sum, but uses the #reduce method to accumulate the sum by adding each value to the previous total.

I hope this helps!

related categories

gistlibby LogSnag