通过 ruby 代码读取和更新 YAML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21422494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading and updating YAML file by ruby code
提问by Joy
I have written a yml file like this:
我写了一个这样的 yml 文件:
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_time 作为 config['last_update'] 访问,但它不起作用。另外我想通过我的 ruby 代码更新 last_update_time ,就像它应该更新一样:
last_update: '2014-01-29 23:59:59'
I have no idea how to do that.
我不知道该怎么做。
回答by Phobos
Switch .load to .load_file and you should be good to go.
将 .load 切换到 .load_file 就可以了。
#!/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.
要写入文件,您需要打开 YAML 文件并写入句柄。像这样的事情应该有效。
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

