【问题标题】:Ruby: Merging two hashes based on keys from one hashRuby:根据一个哈希中的键合并两个哈希
【发布时间】:2017-12-18 02:49:45
【问题描述】:

我有两个哈希

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

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

现在我希望合并以这样一种方式,即来自 hash1 的所有键都存在于最终哈希中,并且如果存在于第二个哈希中的值应该被合并,并且应该删除 hash1 中不存在的任何内容.

所以这个的输出应该是

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

【问题讨论】:

  • 你能展示一下到目前为止你尝试了什么吗?
  • 什么也想不通。尝试使用 zip 功能,深度合并,但无法真正得到任何东西。

标签: ruby hash merge


【解决方案1】:

我想出了以下,不是很漂亮,但就是这样:

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)

结果如下:

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

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

【讨论】:

  • 非常感谢。为我工作:)
  • @AyushMittal 你应该接受这个答案给彼得信用
猜你喜欢
  • 2016-01-06
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 2011-02-21
  • 1970-01-01
  • 2021-02-02
相关资源
最近更新 更多