, bang , Ruby.
module HashRecursive
refine Hash do
def merge(other_hash, recursive=false, &block)
if recursive
block_actual = Proc.new {|key, oldval, newval|
newval = block.call(key, oldval, newval) if block_given?
[oldval, newval].all? {|v| v.is_a?(Hash)} ? oldval.merge(newval, &block_actual) : newval
}
self.merge(other_hash, &block_actual)
else
super(other_hash, &block)
end
end
def merge!(other_hash, recursive=false, &block)
if recursive
self.replace(self.merge(other_hash, recursive, &block))
else
super(other_hash, &block)
end
end
end
end
using HashRecursive
using HashRecursive Hash::merge Hash::merge!, . , .
The new thing is that you can pass a boolean recursive(second argument) to these modified methods and they will merge hashes recursively.
An example to answer the question. It is very simple:
hash_a = { :a => { :b => { :c => "d" } } }
hash_b = { :a => { :b => { :x => "y" } } }
puts hash_a.merge(hash_b)
puts hash_a
hash_a.merge!(hash_b, recursive=true)
puts hash_a
For an advanced example, consider this answer .
Also take a look at my recursive version Hash::each( Hash::each_pair) here .
source
share