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!
Jan 10 ’12

Rails’ Hash#reverse_merge

Ruby’s Hash#merge combines two Hashes, where the second Hash replaces values with the same key of the calling Hash.

Rails adds the method Hash#reverse_merge which keeps the contents of the caller. This gives you - for example - an elegant way to specify default values for an optional argument Hash:

def my_method(options = {})
  options = options.reverse_merge(:option1 => "foo", :option2 => "bar")
  # If you pass in options with the :option1 and :option2 keys,
  # their values will NOT be overwritten.
  # If you leave option1 and option2 out, the defaults passed
  # to reverse_merge will be inserted.
  # actual method implementation here

3 notes 0 comments

  1. rubyquicktips posted this


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