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.
Try this:
or
or
I know I'm excavating this one, but if you happen to use Rails, the
.sum
method can help:Advantage is that it returns
0
on empty hashes:I noticed it was Rails-specific only after typing this answer. I know the OP didn't add the Rails tag, but I figured it might be useful for people stopping by.
Note that as of Ruby 2.4.0,
.sum
is now available.Use
Enumerable#reduce
, if you're ok with gettingnil
if the hash happens to be empty:To safely get
0
when the hash is empty, use:Here's a quick benchmark, for kicks. Note that it appears to be slightly faster to reduce just the values rather than values from the key/value pairs:
You can make
elem
contain the value by splitting it up in 2 variables: