Reduce Hash Values

前端 未结 6 1490
南旧
南旧 2021-02-03 20:30

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

6条回答
  •  时光取名叫无心
    2021-02-03 20:50

    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.

提交回复
热议问题