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

后端 未结 5 1821
無奈伤痛
無奈伤痛 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条回答
  •  旧时难觅i
    2020-12-12 19:50

    The following is slightly faster than @Dan Cheail's for large hashes, and is slightly more functional-programming style:

    new_hash = Hash[old_hash.map {|key, value| key, foo(value)}]
    

    Hash#map creates an array of key value pairs, and Hash.[] converts the array of pairs into a hash.

提交回复
热议问题