深红宝石不同哈希类型
问题描述:
我这个问题挣扎合并,我无法弄清楚如何做到这一点。让我们假设我有两个散列:深红宝石不同哈希类型
hash1 = { "address" => "address", "phone" => "phone }
hash2 = { "info" => { "address" => "x", "phone" => "y"},
"contact_info" => { "info" => { "address" => "x", "phone" => "y"} }}
我希望得到如下的输出:
{ "info" => { "address" => "address", "phone" => "phone"},
"contact_info" => { "info" => { "address" => "address", "phone" => "phone"} }}
我试过Hash#deep_merge
但它并没有解决我的问题。我需要的是能够合并第二个散列表中任何位置的所有键和值的东西,无论它的结构如何。
我该怎么做?任何线索?
答
我想你想递归合并HASH1?也许这:
class Hash
def deep_merge_each_key(o)
self.keys.each do |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"}}}
你的表情是不是一个有效的Ruby对象。你的句子不是有效的英语。此外,它没有任何问题。 – sawa 2013-05-09 16:30:57