Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created December 2, 2010 06:45
Show Gist options
  • Save mattetti/724900 to your computer and use it in GitHub Desktop.
Save mattetti/724900 to your computer and use it in GitHub Desktop.
nest merge hashes
h1 = {:key => {a: 1, b: 2, c: {a: 1, b: 2}}}
h2 = {:key => {c: {a:'a', c: 'c'}, d: 4}}
recursive_merge = lambda do |k, old, new|
(new.respond_to?(:merge) && old.respond_to?(:merge)) ? new.merge(old, &recursive_merge) : new
end
puts h1.merge(h2, &recursive_merge)
# => {:key=>{:a=>1, :b=>2, :c=>{:a=>"a", :b=>2, :c=>"c"}, :d=>4}}
@mattetti
Copy link
Author

mattetti commented Dec 2, 2010

Oops thx Matt, still, is that the best way?

@mtodd
Copy link

mtodd commented Dec 2, 2010

Yeah, I can't think of anything substantially better at present aside from defining a method on Hash. Run with it! :)

@mattetti
Copy link
Author

mattetti commented Dec 2, 2010

Y combinator! I'll try after sleeping some :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment