Read more

Ruby: How to update all values of a Hash

Dominik Schöler
October 30, 2015Software engineer at makandra GmbH

There are many solutions Show archive.org snapshot , but a very concise one is this:

hash.merge!(hash) do |key, old_value, new_value|
  # Return something
end
Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

The block of merge! will be called whenever a key in the argument hash already exists in the base hash. Since hash is updated with itself, each key will conflict and thus allow you to modify the value of each key to whatever you like (by returning old_value you'd get the behavior of Rails' reverse_merge!, by returning new_value you'd get the behavior of standard merge!).

Note that there are better solutions performance-wise.

Posted by Dominik Schöler to makandra dev (2015-10-30 11:31)