2011-12-11 56 views
38

reuse a hash in YAML重用的代碼塊中YAML

Defaults: &defaults 
    Company: Foo 
    Item: 123 

Computer: *defaults 
    Price: 3000 

然而,這將產生錯誤。

是分別定位每個字段值like this的唯一途徑?

Defaults: 
    Company: &company Foo 
    Item: &item 123 

Computer: 
    Company: *company 
    Item: *item 
    Price: 3000 

回答

13
# sequencer protocols for Laser eye surgery 
--- 
- step: &id001     # defines anchor label &id001 
    instrument:  Lasik 2000 
    pulseEnergy:  5.4 
    pulseDuration: 12 
    repetition:  1000 
    spotSize:  1mm 

- step: &id002 
    instrument:  Lasik 2000 
    pulseEnergy:  5.0 
    pulseDuration: 10 
    repetition:  500 
    spotSize:  2mm 

- step: *id001     # refers to the first step (with anchor &id001) 
- step: *id002     # refers to the second step 
- step: *id001 
- step: *id002 

樣品從wikipedia

+1

加布裏埃爾答案是解決這個更好的方法問題。您可以重用整個組,然後覆蓋您想要改變的字段(甚至是深度字段)。 –

172

嘗試通過導入它重用一個完整的組:

Defaults: &defaults 
    Company: foo 
    Item: 123 

Computer: 
    <<: *defaults 
    Price: 3000 

文檔:http://yaml.org/type/merge.html

+15

這真的應該是被接受的答案 – Suan

+1

我總是會忘記這個語法,它有點複雜。 – juanpastas

+0

如果我可以的話,我會投票贊成上百萬,謝謝 –