如何将设置保存为外部文件中的散列? [英] How do I save settings as a hash in a external file?
本文介绍了如何将设置保存为外部文件中的散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我能以某种方式使用它吗
Can I somehow use this
settings = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
在外部文件中作为设置?
in a external file as settings?
如何将其包含在我的脚本中?
How can I include this into my script?
推荐答案
在 Ruby 中存储配置数据最常见的方式是使用 YAML:
The most common way to store configuration data in Ruby is to use YAML:
settings.yml
user1:
path: /
days: 5
user2:
path: /tmp/
days: 3
然后像这样在你的代码中加载它:
Then load it in your code like this:
require 'yaml'
settings = YAML::load_file "settings.yml"
puts settings.inspect
您可以使用 to_yaml
创建 YAML 文件:
You can create the YAML file using to_yaml
:
File.open("settings.yml", "w") do |file|
file.write settings.to_yaml
end
<小时>
也就是说,您也可以使用 load
包含直接的 Ruby 代码:
That said, you can include straight Ruby code also, using load
:
load "settings.rb"
但是,您无法访问文件外的局部变量,因此您必须更改代码以使用实例变量或全局变量:
However, you can't access local variables outside the file, so you would have to change your code to use an instance variable or a global variable:
settings.rb
SETTINGS = {
'user1' => { 'path' => '/','days' => '5' },
'user2' => { 'path' => '/tmp/','days' => '3' }
}
@settings = { 'foo' => 1, 'bar' => 2 }
然后这样加载:
load "settings.rb"
puts SETTINGS.inspect
puts @settings.inspect
这篇关于如何将设置保存为外部文件中的散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文