Created
September 21, 2012 14:52
-
-
Save craigp/3761932 to your computer and use it in GitHub Desktop.
Hash deep merge
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
class Hash | |
def deep_merge(other_hash) | |
Hash.new.replace(self).tap do |new_hash| | |
new_hash.deep_merge!(other_hash) | |
end | |
end | |
def deep_merge!(other_hash) | |
each do |key, val| | |
if val.is_a?(Hash) | |
next unless other_hash.has_key?(key) | |
val.merge_tree!(other_hash[key]) | |
val.merge!(other_hash.delete(key)) if other_hash[key].is_a?(Hash) | |
end | |
end | |
merge!(other_hash) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment