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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)