Ruby deep merge with different hash types -
i'm struggling problem , can't figure out how that. let's suppose have 2 hashes:
hash1 = { "address" => "address", "phone" => "phone } hash2 = { "info" => { "address" => "x", "phone" => "y"}, "contact_info" => { "info" => { "address" => "x", "phone" => "y"} }}
i'd output:
{ "info" => { "address" => "address", "phone" => "phone"}, "contact_info" => { "info" => { "address" => "address", "phone" => "phone"} }}
i've tried hash#deep_merge
not solve problem. need merge keys , values anywhere in second hash whatever it's structure is.
how can that? clues?
i think want recursively merge hash1? maybe this:
class hash def deep_merge_each_key(o) self.keys.each |k| if o.has_key?(k) self[k] = o[k] elsif self[k].is_a?(hash) self[k].deep_merge_each_key(o) end end self end end h1 = {"address"=>"address", "phone"=>"phone"} h2 = { "info" => { "address" => "x", "phone" => "y"}, "contact_info" => { "info" => { "address" => "x", "phone" => "y"} } } puts h2.deep_merge_each_key(h1).inspect # => {"info"=>{"address"=>"address", "phone"=>"phone"}, "contact_info"=>{"info"=>{"address"=>"address", "phone"=>"phone"}}}
Comments
Post a Comment