Ruby: What is the easiest method to update Hash values?

后端 未结 5 1822
無奈伤痛
無奈伤痛 2020-12-12 19:14

Say:

h = { 1 => 10, 2 => 20, 5 => 70, 8 => 90, 4 => 34 }

I would like to change each value v to foo(v

5条回答
  •  被撕碎了的回忆
    2020-12-12 19:39

    You can use update (alias of merge!) to update each value using a block:

    hash.update(hash) { |key, value| value * 2 }
    

    Note that we're effectively merging hash with itself. This is needed because Ruby will call the block to resolve the merge for any keys that collide, setting the value with the return value of the block.

提交回复
热议问题