How do you save values into a YAML file?

freedom picture freedom · Jan 26, 2013 · Viewed 52.9k times · Source

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

Answer

Christophe Biocca picture Christophe Biocca · Jan 26, 2013

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