I have two YAML files from i18n, where certain keys in the first file are overwritten in the second file. I want to merge this two YAML files into one, so I read the two files into a hash, and tried to merge them:
a = {
en: {
test: {
bar: "bar",
foo: "foo"
}
}
}
b = {
en: {
test: {
bar: "hello world"
}
}
}
a.merge!(b)
puts a
# => {:de=>{:test=>{:bar=>"hello world"}}}
#
# but should return
# => {:de=>{:test=>{:bar=>"hello world", :foo => "foo"}}}
The problem is, that the parent key test gets completely overwritten. Is there an easy way to only overwrite bar but keep the key/value from foo?
(this are just examples, the nesting is deeper for some keys, 4 or 5 levels deep)
You are looking for a deep_merge method (or its banged sibling). Luckily, it is already defined in rails:
a.deep_merge!(b)
a #=> {:en=>{:test=>{:bar=>"hello world", :foo=>"foo"}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With