Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you save values into a YAML file? [duplicate]

Inside my persist.yml file. I have the following key-value pair...

session = 0

How do I update the YAML file such that:

session = 2
like image 249
freedom Avatar asked Jan 26 '13 01:01

freedom


People also ask

Does YAML allow duplicate keys?

Duplicate keys in YAML files are not allowed in the spec (https://yaml.org/spec/1.2.2/#nodes, https://yaml.org/spec/1.0/#model-node), but the older version of symfony/yaml does not complain about them.

How do I save changes in YAML file?

you can exit the vi editor and save the changes using the : wq ( write and quit ) command .


1 Answers

Using ruby-1.9.3 (Approach may not work in older versions).

I'm assuming the file looks like this (adjust code accordingly):

---
content:
    session: 0

and is called /tmp/test.yml

Then the code is just:

require 'yaml' # Built in, no gem required
d = YAML::load_file('/tmp/test.yml') #Load
d['content']['session'] = 2 #Modify
File.open('/tmp/test.yml', 'w') {|f| f.write d.to_yaml } #Store
like image 93
Christophe Biocca Avatar answered Oct 18 '22 03:10

Christophe Biocca