ruby 如何将值保存到 YAML 文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14532959/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:42:08  来源:igfitidea点击:

How do you save values into a YAML file?

rubyruby-on-rails-3yaml

提问by freedom

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

在我的 persist.yml 文件中。我有以下键值对...

session = 0

How do I update the YAML file such that:

如何更新 YAML 文件,以便:

session = 2

回答by Christophe Biocca

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

使用 ruby​​-1.9.3(方法可能不适用于旧版本)。

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

我假设文件看起来像这样(相应地调整代码):

---
content:
    session: 0

and is called /tmp/test.yml

并被称为 /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