如何更新嵌套映射yml下的值

时间:2015-03-05 08:08:26

标签: ruby-on-rails ruby

我有一个像下面的yml。

ss_usecase_1:
  -    
       key1: "val1" 
       key2: "val2" 
       key3: "45x" 
       key4: 11.26.44.23
       key5: "admin" 
       key6: "CUP" 
       key7: 960

ss_usecase_2:
  -    
       key1: "val3" 
       key2: "val4" 
       key3: "aby45" 
       key4: 11.25.4.26
       key5: "admin" 
       key6: "CUP" 
       key7: 962

我想更新ss_usecase_2下的key6。以下是我尝试更新yml的方式,但它完全破坏了我的yml。在此过程中,主密钥的“ss_usecase_1”和“ss_usecase_2”都消失了

dump_data=YAML::load(File.open("path to yml"))
data=dump_data['ss_usecase_1'][0]

data['key6']="cup1"
File.open("data/synched_services/usecase_1.yml", 'w') { |f| YAML.dump(data, f) }

有没有有效的方法可以在不打扰我的yml数据的情况下做到这一点?

2 个答案:

答案 0 :(得分:0)

如果您不希望dump_data被操纵,请使用clone

data = dump_data['ss_usecase_1'][0].clone
  

(clone)生成obj的浅表副本 - obj的实例变量   复制,但不是他们引用的对象。克隆复制冻结   和被污染的状态。

解释示例:

dump_data['ss_usecase_1'][0]
# => {"key1"=>"val1", "key2"=>"val2", "key3"=>"45x", "key4"=>"11.26.44.23", "key5"=>"admin", "key6"=>"cup1", "key7"=>960}

data = dump_data['ss_usecase_1'][0]
data["key1"] = "abc"
dump_data['ss_usecase_1'][0]
# => {"key1"=>"abc", "key2"=>"val2", "key3"=>"45x", "key4"=>"11.26.44.23", "key5"=>"admin", "key6"=>"cup1", "key7"=>960} 
#notice key1 is getting changed for dump_data too

使用clone的相同示例:

data = dump_data['ss_usecase_1'][0].clone
data["key1"] = "abc"
dump_data['ss_usecase_1'][0]
# => {"key1"=>"val1", "key2"=>"val2", "key3"=>"45x", "key4"=>"11.26.44.23", "key5"=>"admin", "key6"=>"cup1", "key7"=>960} 
#notice key1 is unchanged

答案 1 :(得分:0)

以下是工作示例:

require 'yaml'

data = YAML::load(File.open('1.yml')) # loading 1.yml into data variable
data['ss_usecase_2'][0]['key6'] = 'cup1' # changing key6 under ss_usecase_2
File.open('2.yml', 'w') { |file| file.write(data.to_yaml) } # saving to 2.yml

如果要覆盖现有文件,只需在File.open条指令中指定。