ruby deep merge
hash1 = { "a" => 100, "b" => { "x" => 200, "y" => 300 } }
hash2 = { "b" => { "y" => 400, "z" => 500 }, "c" => 600 }
merged_hash = hash1.merge(hash2) { |key, oldval, newval| oldval.merge(newval) }
This code snippet initializes two hashes hash1
and hash2
. Then, it uses the merge
method on hash1
with hash2
as an argument and a block. In the block, it specifies that if there's a conflict (if keys are the same in both hashes), the values should be merged recursively using the merge
method. This creates a new hash merged_hash
containing the merged values from hash1
and hash2
, where conflicting keys are merged deeply according to the block provided.