Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
May 4 ’11

Merge or reverse_merge a Hash

Ruby’s Hash#merge lets you merge two Hashes. Duplicate entries in the merged Hash taking precedence over then ones in the calling Hash:

h1 = { "a" => 100, "b" => 200 }
h2 = { "b" => 254, "c" => 300 }
h1.merge(h2)   #=> {"a"=>100, "b"=>254, "c"=>300}
h1             #=> {"a"=>100, "b"=>200}

Rails’ Hash#reverse_merge takes the opposite approach when it comes to handle duplicate entries. The API docs perfectly describe what it’s good for, giving an example of a very common practise regarding a method’s options:

Allows for reverse merging two hashes where the keys in the calling hash take precedence over those in the other_hash. This is particularly useful for initializing an option hash with default values:

def setup(options = {})
  options.reverse_merge! :size => 25, :velocity => 10
end

Using merge, the above example would look as follows:

def setup(options = {})
  { :size => 25, :velocity => 10 }.merge(options)
end

The default :size and :velocity are only set if the options hash passed in doesn’t already have the respective key.

Both methods are also available in their Bang versions merge! and reverse_merge!.

Here are the docs: Hash#merge (Ruby) and Hash#reverse_merge (Rails).

All code examples taken from the respective API docs.

11 notes 0 comments

  1. kxhitiz reblogged this from rubyquicktips
  2. count0 reblogged this from rubyquicktips
  3. rubyquicktips posted this

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus