Reduce Hash Values
I am having trouble with the syntax for reduce. I have a hash of the following format: H = {"Key1" => 1, "Key2" => 2} I would like to use reduce to find the sum of the values in this function. Something Like H.reduce(0) {|memo, elem| memo+=elem} I know this is wrong. I dont understand how I can make elem the value of the hash. Use Enumerable#reduce , if you're ok with getting nil if the hash happens to be empty: H.values.reduce(:+) # => 3 Hash.new.values.reduce(:+) # => nil To safely get 0 when the hash is empty, use: H.values.reduce(0) { |sum,x| sum + x } # or... H.reduce(0) { |sum,(key,val)|