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

Rails (and Ruby 2.4+ natively) have Hash#transform_values, so you can now do {a:1, b:2, c:3}.transform_values{|v| foo(v)}

https://ruby-doc.org/core-2.4.0/Hash.html#method-i-transform_values

If you need it to work in nested hashes as well, Rails now has deep_transform_values(source):

hash = { person: { name: 'Rob', age: '28' } }

hash.deep_transform_values{ |value| value.to_s.upcase }
# => {person: {name: "ROB", age: "28"}}

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.

Tags:

Ruby

Hash