Update value of key of a yaml file in ruby on rail

2019-01-21 19:27发布

问题:

I have a yml file with some key value.

age: 24
Name: XYZ

I want code to update the value of "Name" key from XYZ to ABC? How can i do it?

回答1:

    data = YAML.load_file "path/to/yml_file.yml"
    data["Name"] = ABC
    File.open("path/to/yml_file.yml", 'w') { |f| YAML.dump(data, f) }

It will write into yml file. If specified key ("Name") is not present in file, it will write new key value othrwise the existing one will be replaced.