Skip to content

Instantly share code, notes, and snippets.

@fronx
Created December 1, 2009 16:55
Show Gist options
  • Save fronx/246436 to your computer and use it in GitHub Desktop.
Save fronx/246436 to your computer and use it in GitHub Desktop.
class Hash
def nested_merge(other)
result = self
other.each do |key, value|
if Hash === self[key] && Hash === other[key]
result[key] = self[key].nested_merge(other[key])
else
result[key] = other[key]
end
end
result
end
end
describe Hash, :nested_merge do
it "should return a merged hash" do
a = {:a => 1, :b => {:c => 1, :d => {:foo => 'bar'}, :abc => 'boo'}}
b = {:a => 2, :b => {:c => 'x', :d => {:foo => 'xx'}}, :y => 'y'}
a.nested_merge(b).should ==
{
:a => 2,
:b => {
:c => 'x',
:d => {:foo => 'xx'},
:abc => 'boo'
},
:y => 'y'
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment