How do you save values into a YAML file?

RubyRuby on-Rails-3Yaml

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfreedomView Question on Stackoverflow
Solution 1 - RubyChristophe BioccaView Answer on Stackoverflow