Reduce Hash Values

前端 未结 6 1476
南旧
南旧 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:51

    In case of a complex hash it might be easier to map it first to an array of values, then reduce:

    values = H.map do |k, v|
        # some complex logic here
    end
    values.reduce(:+)
    

    Or values.reduce(0, :+) if the array might be empty.

提交回复
热议问题