我在Ruby on Rails项目中有以下yml文件表示本地化文件:
es:
animals:
happy_animals:
dog: Dog
cat: Cat
horse: Horse
sad_animals:
cow: Cow
elephant: Elephant
我需要在与动物相同的级别添加另一个类别以获得以下结果:
es:
animals:
happy_animals:
dog: Dog
cat: Cat
horse: Horse
sad_animals:
cow: Cow
elephant: Elephant
farm_animals: # This key is new
happy_animals:
dog: Dog
cat: Cat
horse: Horse
sad_animals:
cow: Cow
elephant: Sick elephant #This value changed
我想知道是否有办法复制结构,覆盖某些特定的值或节点。我尝试过以下方法:
es:
animals: &animals
happy_animals:
dog: Dog
cat: Cat
horse: Horse
sad_animals:
cow: Cow
elephant: Elephant
farm_animals:
<<: *animals
sad_animals:
elephant: Sick Elephant
但是,这段代码会覆盖树的整个sad_animals分支,而我只想覆盖一个特定的值,保留树的其余部分。这是否可以与yaml一起使用?
答案 0 :(得分:0)
这应该可以解决问题:
es:
animals: &animals
happy_animals:
dog: Dog
cat: Cat
horse: Horse
sad_animals: &sad_animals
cow: Cow
elephant: Elephant
farm_animals:
<<: *animals
sad_animals:
<<: *sad_animals
elephant: Sick Elephant
2.3.0 :001 > yaml = <<-YALM
2.3.0 :002"> es:
2.3.0 :003"> animals: &animals
2.3.0 :004"> happy_animals:
2.3.0 :005"> dog: Dog
2.3.0 :006"> cat: Cat
2.3.0 :007"> horse: Horse
2.3.0 :008"> sad_animals: &sad_animals
2.3.0 :009"> cow: Cow
2.3.0 :010"> elephant: Elephant
2.3.0 :011"> farm_animals:
2.3.0 :012"> <<: *animals
2.3.0 :013"> sad_animals:
2.3.0 :014"> <<: *sad_animals
2.3.0 :015"> elephant: Sick Elephant
2.3.0 :016"> YALM
2.3.0 :017"> Psych.load yaml
=> {"es"=>{"animals"=>{"happy_animals"=>{"dog"=>"Dog", "cat"=>"Cat", "horse"=>"Horse"}, "sad_animals"=>{"cow"=>"Cow", "elephant"=>"Elephant"}}, "farm_animals"=>{"happy_animals"=>{"dog"=>"Dog", "cat"=>"Cat", "horse"=>"Horse"}, "sad_animals"=>{"cow"=>"Cow", "elephant"=>"Sick Elephant"}}}}
如您所见,sad_animals
有一个Sick Elephant
:
"sad_animals"=>{"cow"=>"Cow", "elephant"=>"Sick Elephant"}