A left merge versus a right merge

Recently, I found out that you can set the default winner in a merge for a hash. I wasn’t going to write about it since I figured it was pretty basic. But then again, I hadn’t written in a while. Been busy. So something easy to get me back on the wagon.

I’ll call it a left merge and a right merge. Let’s say we have some options, like default options and new options in a method, and we want merge them together, where options override default options, but you store it into options.

# some options
default_opts = { :a => 1, :b => 2 }
opts = { :b => 3, :c => 4 }

Well, the normal way of merging things won’t work:

# the normal default merge
opts.merge!(default_opt) # => { :a => 1, :b => 2, :c => 4 }

Well, that’s not right. We want the default options to be overridden by the new options and store it in the opts variable. We could do it like this:

# one way of doing things
opts = default_opts.merge(opts) # => { :a => 1, :b => 3, :c => 4 }

But then here’s another

# the other merge
opts.merge!(default_opts) { |k,o| o } # => { :a => 1, :b => 3, :c => 4 }



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s