Ruby: 深度合并 yaml 文件而不覆盖父文件

Ruby: Deep merge yaml files without overwriting parent

我有两个来自 i18n 的 YAML 文件,其中第一个文件中的某些键在第二个文件中被覆盖。我想将这两个 YAML 文件合并为一个,所以我将这两个文件读入一个哈希,并尝试合并它们:

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

问题是,父键 test 被完全覆盖。有没有一种简单的方法可以只覆盖 bar 但保留 foo 中的 key/value?

(这只是例子,有些键的嵌套更深,4或5层深)

在你的代码中你合并了 en。与测试哈希合并:

a[:en][:test].merge!(b[:en][:test])
# => {:en=>{:test=>{:bar=>"hello world", :foo=>"foo"}}}

您正在寻找 deep_merge 方法(或其 banged 兄弟)。幸运的是,它已经在 rails:

中定义了
a.deep_merge!(b)
a #=> {:en=>{:test=>{:bar=>"hello world", :foo=>"foo"}}}