find the sum of all values in a map in ruby

To find the sum of all values in a map in Ruby, you can use the inject method. Here's an example:

main.rb
my_map = {"apple" => 1, "banana" => 2, "orange" => 3}

sum = my_map.values.inject(:+)
puts sum #=> 6
101 chars
5 lines

In this example, my_map is a map with string keys and integer values. The values method returns an array of all the values in the map ([1, 2, 3] in this case), and inject(:+) iterates through the array and adds each element to the sum. The result is the sum of all values in the map (6 in this case).

related categories

gistlibby LogSnag