Ruby深度合并不同的哈希类型

时间:2013-05-09 16:19:47

标签: ruby hash

我正在努力解决这个问题,我无法弄清楚如何做到这一点。我们假设我有两个哈希:

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,但它并没有解决我的问题。我需要的东西是将所有键和值合并到第二个散列中的任何位置,无论它的结构如何。

我该怎么做?有线索吗?

1 个答案:

答案 0 :(得分: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"}}}