-1

我正在努力解决这个问题,但我不知道该怎么做。假设我有两个哈希:

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,但它并没有解决我的问题。我需要的是可以合并第二个哈希中任何位置的所有键和值的东西,无论它的结构是什么。

我怎样才能做到这一点?有什么线索吗?

4

1 回答 1

2

我想你想递归地合并 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"}}}
于 2013-05-09T16:59:22.873 回答