Created
December 2, 2010 06:45
-
-
Save mattetti/724900 to your computer and use it in GitHub Desktop.
nest merge hashes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}} |
Yeah, I can't think of anything substantially better at present aside from defining a method on Hash. Run with it! :)
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
Oops thx Matt, still, is that the best way?