如何将 yaml 文件解析为 ruby​​ 哈希和/或数组?

发布于 2024-09-14 11:05:35 字数 42 浏览 11 评论 0原文

我需要将 yaml 文件加载到 Hash 中,
我应该怎么办?

I need to load a yaml file into Hash,
What should I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

晨曦慕雪 2024-09-21 11:05:35

我会使用类似的东西:

hash = YAML.load(File.read("file_path"))

I would use something like:

hash = YAML.load(File.read("file_path"))
对你而言 2024-09-21 11:05:35

维纳布尔斯答案的一个简单版本:

hash = YAML.load_file("file_path")

A simpler version of venables' answer:

hash = YAML.load_file("file_path")
听风念你 2024-09-21 11:05:35

使用 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

Use the YAML module:
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

旧人哭 2024-09-21 11:05:35

您可能会遇到 此相关问题中提到的问题,即 YAML 文件或流指定 YAML 加载器将其放入其中的对象将尝试将数据转换为。问题是您需要一个了解相关对象的相关 Gem。

我的解决方案非常简单,是作为该问题的答案提供的。这样做:

yamltext = File.read("somefile","r")
yamltext.sub!(/^--- \!.*$/,'---')
hash = YAML.load(yamltext)

本质上,您从 yaml 文本中删除对象分类器文本。然后你解析/加载它。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文