如何将 yaml 文件解析为 ruby 哈希和/或数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3481652/
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
How to parse a yaml file into ruby hashs and/or arrays?
提问by Croplio
I need to load a yaml file into Hash,
What should I do?
我需要将一个 yaml 文件加载到 Hash 中,
我该怎么办?
采纳答案by NullUserException
Use the YAML module:
http://ruby-doc.org/stdlib-1.9.3/libdoc/yaml/rdoc/YAML.html
使用 YAML 模块:http:
//ruby-doc.org/stdlib-1.9.3/libdoc/yaml/rdoc/YAML.html
node = YAML::parse( <<EOY )
one: 1
two: 2
EOY
puts node.type_id
# prints: 'map'
p node.value['one']
# prints key and value nodes:
# [ #<YAML::YamlNode:0x8220278 @type_id="str", @value="one", @kind="scalar">,
# #<YAML::YamlNode:0x821fcd8 @type_id="int", @value="1", @kind="scalar"> ]'
# Mappings can also be accessed for just the value by accessing as a Hash directly
p node['one']
# prints: #<YAML::YamlNode:0x821fcd8 @type_id="int", @value="1", @kind="scalar">
http://yaml4r.sourceforge.net/doc/page/parsing_yaml_documents.htm
http://yaml4r.sourceforge.net/doc/page/parsing_yaml_documents.htm
回答by venables
I would use something like:
我会使用类似的东西:
hash = YAML.load(File.read("file_path"))
回答by Duncan X Simpson
A simpler version of venables' answer:
venables 回答的更简单版本:
hash = YAML.load_file("file_path")
回答by Otheus
You may run into a problem mentioned at this related question, namely, that the YAML file or stream specifies an object into which the YAML loader will attempt to convert the data into. The problem is that you will need a related Gem that knows about the object in question.
您可能会遇到此相关问题中提到的问题,即 YAML 文件或流指定了一个对象,YAML 加载程序将尝试将数据转换为该对象。问题是你需要一个相关的 Gem 来了解所讨论的对象。
My solution was quite trivial and is provided as an answer to that question. Do this:
我的解决方案非常简单,并作为该问题的答案提供。做这个:
yamltext = File.read("somefile","r")
yamltext.sub!(/^--- \!.*$/,'---')
hash = YAML.load(yamltext)
In essence, you strip the object-classifier text from the yaml-text. Then you parse/load it.
本质上,您从 yaml 文本中去除了对象分类器文本。然后你解析/加载它。

