Skip to content

Instantly share code, notes, and snippets.

@craigp
Created September 21, 2012 14:52
Show Gist options
  • Save craigp/3761932 to your computer and use it in GitHub Desktop.
Save craigp/3761932 to your computer and use it in GitHub Desktop.
Hash deep merge
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