Reduce Hash Values

前端 未结 6 1541
南旧
南旧 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 21:15

    h = {"Key1" => 1, "Key2" => 2}
    
    h.values.inject(0){|f,v| f += v.to_i }
    # => 3
    

    or

    h.values.inject(:+)
    # => 3
    

提交回复
热议问题