Reduce Hash Values

richsoni picture richsoni · Dec 14, 2012 · Viewed 37.3k times · Source

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.

Answer

steenslag picture steenslag · Dec 14, 2012

You can make elem contain the value by splitting it up in 2 variables:

H.reduce(0) {|memo, (key, val)| memo += val}