Ruby-on-rails YAML 文件中的哈希?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3034072/
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
Hash inside YAML file?
提问by Yuval Karmi
I want to include a hash and list inside a YAML file that I'm parsing with the following command:
我想在我使用以下命令解析的 YAML 文件中包含一个哈希和列表:
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")
My YAML file looks like this:
我的 YAML 文件如下所示:
feeds: [{:url => 'http://www.google.com', :label => 'default'}]
But this doesn't seem to work. How would I go about achieving such a thing?
但这似乎不起作用。我将如何去实现这样的事情?
Thanks, Yuval
谢谢,尤瓦尔
EDIT: Sorry, guys. I'm still unclear about how to do this and I suspect it is in part due to my somewhat vague phrasing. I asked a better-phrased, more broad question here. Thank you!
编辑:对不起,伙计们。我仍然不清楚如何做到这一点,我怀疑部分原因是我的措辞有些含糊。我在这里问了一个措辞更好、更广泛的问题。谢谢!
回答by Ceilingfish
You can mark it up like this
你可以像这样标记它
feeds:
-
url: 'http://www.google.com'
label: 'default'
Note the spacing is important here. "-" must be indented by a single space (not a tab), and followed by a single space. And url& labelmust be indented by two spaces (not tabs either).
注意这里的间距很重要。"-" 必须缩进一个空格(不是制表符),后跟一个空格。并且url&label必须缩进两个空格(也不是制表符)。
Additionally this might be helpful: http://www.yaml.org/YAML_for_ruby.html
此外,这可能会有所帮助:http: //www.yaml.org/YAML_for_ruby.html
回答by jpoppe
Ceilingfish's answer is maybe technically correct, but he recommends to use a white space at the end of a line. This is prone to errors and is not a good practice!
Ceilingfish 的回答在技术上可能是正确的,但他建议在行尾使用空格。这很容易出错,不是一个好习惯!
This is how I would do it:
这就是我将如何做到的:
Create a settings.yaml file with the following contents:
创建一个包含以下内容的 settings.yaml 文件:
---
feeds:
:url: 'http://www.google.com'
:label: 'default'
This will create the following hash after the YAML file has been loaded:
这将在加载 YAML 文件后创建以下哈希:
irb(main):001:0> require 'yaml'
=> true
irb(main):002:0> YAML.load_file('settings.yaml')
=> {"feeds"=>{:url=>"http://www.google.com", :label=>"default"}}
irb(main):003:0>
In this example, I also use symbols since this seems to be the preferred way of storing Ruby keys in Ruby.
在这个例子中,我也使用了符号,因为这似乎是在 Ruby 中存储 Ruby 密钥的首选方式。
回答by estan
Old question, but since I was in a similar spot... Like Jasper pointed out, Ceilingfish's answer is correct. But you can also do
老问题,但由于我处于类似的位置......就像贾斯珀指出的那样,Ceilingfish 的回答是正确的。但你也可以这样做
feeds:
- url: 'http://www.google.com'
label: 'default'
to avoid having to rely on trailing whitespace after the dash.
避免必须依赖破折号后的尾随空格。

