Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Deep merge yaml files without overwriting parent

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)

like image 363
23tux Avatar asked Mar 24 '26 21:03

23tux


1 Answers

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"}}}
like image 92
BroiSatse Avatar answered Mar 26 '26 13:03

BroiSatse