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 t
I know I'm excavating this one, but if you happen to use Rails, the .sum method can help:
H = {"Key1" => 1, "Key2" => 2}
=> {"Key1"=>1, "Key2"=>2}
> H.values.sum
=> 3
Advantage is that it returns 0
on empty hashes:
> {}.values.sum
=> 0
> {}.values.reduce(:+)
=> nil
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.