Reading and updating YAML file by ruby code

2019-03-11 01:47发布

问题:

I have written a yml file like this:

last_update: '2014-01-28 11:00:00'

I am reading this file as

config = YAML.load('config/data.yml')

Later I am accessing the last_update_time as config['last_update'] but it is not working. Also I want to update last_update_time by my ruby code like it should update like:

 last_update: '2014-01-29 23:59:59' 

I have no idea how to do that.

回答1:

Switch .load to .load_file and you should be good to go.

#!/usr/bin/env ruby
require 'yaml'
config = YAML.load_file('data.yml')
puts config['last_update']

After running this is what I get

orcus:~ user$ ruby test.rb
# ⇒ some_data

To write the file you will need to open the YAML file and write to the handle. Something like this should work.

require 'yaml'
config = YAML.load_file('data.yml')
puts config['last_update'] #in my file this is set to "some data"
config['last_update'] = "other data"
File.open('data.yml','w') do |h| 
   h.write config.to_yaml
end

Output was

orcus:~ user$ ruby test.rb
some data
orcus:~ user$ cat data.yml
---
last_update: other data