Merge nested hash without overwritting in Ruby

孤街醉人 提交于 2020-06-18 04:01:08

问题


After checking this Ruby convert array to nested hash and other sites I am not able to achieve the following convertion:

I have this:

{"a"=>"text"}
{"b"=>{"x"=>"hola"}}
{"b"=>{"y"=>"pto"}

}

and I want to obtain:

{"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

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.

Update:

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"}},
    ...
}

回答1:


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

Now,

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"}}



回答2:


You could use merge with a block to tell Ruby how to handle duplicate keys:

a = {"a"=>"text"}
b = {"b"=>{"x"=>"hola"}}
c = {"b"=>{"y"=>"pto"}}

a.merge(b).merge(c) { |key, left, right| left.merge(right) }
#=> {"a"=>"text", "b"=>{"x"=>"hola", "y"=>"pto"}}


来源:https://stackoverflow.com/questions/32268739/merge-nested-hash-without-overwritting-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!