Skip to content

Instantly share code, notes, and snippets.

@daniel-jacob-pearson
Last active September 13, 2016 14:22
Show Gist options
  • Save daniel-jacob-pearson/ab66f55fd38d664b6198379c9116a8f0 to your computer and use it in GitHub Desktop.
Save daniel-jacob-pearson/ab66f55fd38d664b6198379c9116a8f0 to your computer and use it in GitHub Desktop.
Deep Merge: transliterated from https://gist.github.com/dpatti/178bd9948518256396ff
# Deep merge
#
# - Write a function that takes two hashes and returns a new hash containing the
# keys and values from both hashes.
# - Neither input should be modified.
# - If the key exists in both hashes...
# ...merge the values if they are both hashes.
# ...give the values in the second hash (b) precedence otherwise.
def merge(a, b)
# replace with your solution
end
# Input for tests
a = {
"hello" => "who?",
"foo" => {
"bar" => 1,
},
"first" => true,
}
b = {
"hello" => "world!",
"foo" => {
"baz" => 2,
},
"second" => false,
}
expected = {
"hello" => "world!",
"foo" => {
"bar" => 1,
"baz" => 2,
},
"first" => true,
"second" => false,
}
# Test that the merge gives us the expected results
result = merge(a, b)
unless result == expected
puts 'expected:', expected.inspect, 'result:', result.inspect
raise RuntimeError, 'unexpected results'
end
# Test that we have not modified the input
raise RuntimeError, 'the first input was modified' unless a == {
"hello" => "who?",
"foo" => {
"bar" => 1,
},
"first" => true,
}
raise RuntimeError, 'the second input was modified' unless b == {
"hello" => "world!",
"foo" => {
"baz" => 2,
},
"second" => false,
}
puts "All tests pass!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment