Saturday, June 05, 2010

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.

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

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

1 # the normal default merge 2 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:

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

But then here’s another

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

Yay!

Posted via web from The Web and all that Jazz

No comments:

Post a Comment