Last active
September 13, 2016 14:22
-
-
Save daniel-jacob-pearson/ab66f55fd38d664b6198379c9116a8f0 to your computer and use it in GitHub Desktop.
Deep Merge: transliterated from https://gist.github.com/dpatti/178bd9948518256396ff
This file contains hidden or 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
# 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