合并嵌套哈希而不在Ruby中覆盖 [英] Merge nested hash without overwritting in Ruby
问题描述
选中此 Ruby将数组转换为嵌套哈希和其他网站无法实现以下转换:
After checking this Ruby convert array to nested hash and other sites I am not able to achieve the following convertion:
我有这个:
{"a"=>"text"}
{"b"=>{"x"=>"hola"}}
{"b"=>{"y"=>"pto"}
}
我想获得:
{"a"=>text,
b=>{"x" => "hola",
"y" => "pto"
}
}
直到现在,代码看起来像这样:
Until now the code seems like this:
tm =[[["a"],"text"],[["b","x"],"hola"],[["b","y"],"pto"]]
q = {}
tm.each do |l|
q = l[0].reverse.inject(l[1]) { |p, n| { n => p } }
i += 1
end
我尝试使用merge
,但是它会覆盖密钥!我也尝试过如何合并两次哈希没有在Ruby中覆盖重复的键?,但是它会不断覆盖.
I tried with merge
, but it overwrites the keys!. I tried also this How can I merge two hashes without overwritten duplicate keys in Ruby? but it keeps overwritting.
更新:
如何为未定义的嵌套哈希(级别)执行此操作? hash[key1][key2][key3]... = "value"
How can I do it for an undefined nested hash (level) ? hash[key1][key2][key3]... = "value"
{"a"=>"text"},
{"b"=>{"x"=>"hola"},
{"b"=>{"y"=>"pto"},
{"c"=>{"g"=>{"k" => "test1"}},
...
}
推荐答案
For Rails there is the deep_merge
function for ActiveSupport
that does exactly what you ask for.
您可以自己实现以下目标:
You can implement the same for yourself as follows:
class ::Hash
def deep_merge(second)
merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 }
self.merge(second, &merger)
end
end
现在
h1 = {"a"=>"text"}
h2 = {"b"=>{"x"=>"hola"}}
h3 = {"b"=>{"y"=>"pto"}}
h1.deep_merge(h2).deep_merge(h3)
# => {"a"=>"text", "b"=>{"x"=>"hola", "y"=>"pto"}}
这篇关于合并嵌套哈希而不在Ruby中覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!