Skip to content

Instantly share code, notes, and snippets.

@mwmitchell
Created May 19, 2009 01:26
Show Gist options
  • Save mwmitchell/113858 to your computer and use it in GitHub Desktop.
Save mwmitchell/113858 to your computer and use it in GitHub Desktop.
# A module (for including into the core Ruby Hash class) which performs deep merging,
# but only replaces a value if the replacement value is not nil.
# Operates on object references: friendly_deep_merge!, or copies: friendly_deep_merge
# Also does reverse merging; a hash can be updated only if its own values aren't nil.
module FriendlyDeepMerge
def friendly_deep_merge(hash)
target = dup
hash.keys.each do |key|
if hash[key].is_a? Hash and self[key].is_a? Hash
target[key] = target[key].friendly_deep_merge(hash[key])
next
end
target[key] = hash[key] unless hash[key].nil?
end
target
end
def friendly_deep_merge!(second)
second.each_pair do |k,v|
if self[k].is_a?(Hash) and second[k].is_a?(Hash)
self[k].friendly_deep_merge!(second[k])
else
self[k] = second[k] unless second[k].nil?
end
end
end
def reverse_friendly_deep_merge(other_hash)
other_hash.friendly_deep_merge(self)
end
def reverse_friendly_deep_merge!(other_hash)
replace(reverse_friendly_deep_merge(other_hash))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment