Ruby:根据一个哈希中的键合并两个哈希值

时间:2017-07-13 10:56:54

标签: ruby hash merge

我有两个哈希

hash1 = {"a" => { "b" => {}, "c" => {}} , "d" => { "e" => {} } }

hash2 = {"a" => { "b" => {"x" => "y"}, "z" => 1}}

现在我希望合并的方式是hash1中的所有键都存在于最终的哈希中,并且第二个哈希中存在的值应该合并,并且应该删除hash1中不存在的任何内容

所以这个的输出应该是

final_hash = {"a" => { "b" => {"x" => "y"}, "c" => {}} , "d" => { "e" => {} } }

1 个答案:

答案 0 :(得分:0)

我想出了以下内容,不是很漂亮,但现在是:

"\s"

以下是结果:

require 'pp'

hash1 = {"a" => {"b" => {}, "c" => {}}, "d" => {"e" => {}}}
hash2 = {"a" => {"b" => {"x" => "y"}, "z" => 1}}

final_hash = {"a" => {"b" => {"x" => "y"}, "c" => {}}, "d" => {"e" => {}}}

puts
pp hash1
pp hash2

class Hash

  def mittal_merge(source)
    result = {}

    keys.each do |key|
      value = {}

      self[key].keys.each do |sub_key|
        value[sub_key] = (source[key] || {})[sub_key] || {}
      end

      result[key] = value
    end

    result
  end


end

puts
pp final_hash
pp hash1.mittal_merge(hash2)