Ruby 中的 YAML 解析:如何仅获取某种类型的元素? [英] YAML parsing in Ruby: How to get only a certain type of elements?
问题描述
我有以下 YAML:
- name: List of monkeys
- author: Nicolas Raoul
- version: 2
- monkey:
- name: Chee-Chee
- age: 2
- monkey:
- name: Curious George
- age: 6
- food: bananas
- monkey:
- name: Mojo
- food: peanuts
在 Ruby 中,如何获取猴子?
序言中元数据参数的数量(姓名、作者、...)是可变的.
In Ruby, how to get the monkeys?
The number of metadata parameters in the preamble (name, author, ...) is variable.
它会返回如下内容:
[{"monkey"=>[{"name"=>"Chee-Chee"}, {"age"=>2}]}, {"monkey"=>[{"name"=>"Curious George"}, {"age"=>6}, {"food"=>"bananas"}]}, {"monkey"=>[{"name"=>"Mojo"}, {"food"=>"peanuts"}]}]
在 XML/XPath 中,我会简单地编写 /monkey
,但是 YAML/Ruby 的语法是什么?
In XML/XPath I would simply write /monkey
, but what is the syntax with YAML/Ruby ?
注意:我不想创建一个包含所有猴子作为子项的monkeys
节点,因为有很多猴子,客户端会编辑文件添加更多,所以我想让文件非常简单.我是 YAML 的新手,所以可能需要一个更好的组织,但简洁是最重要的,特别是我不想增加子级别的数量.
Note: I don't want to create a monkeys
node containing all monkeys as sub-items, because there are many monkeys and the clients will edit the file to add more, so I want to keep the file really simple. I am new to YAML so a better organization might be needed, but brevity is paramount, in particular I don't want to increase the number of sub-levels.
推荐答案
您可以使用 Enumerator 的 #select
方法只返回集合中的猴子.如果您在一个名为 your_yaml
的变量中解析了 YAML 对象,则此代码将返回您所要求的内容:
You can use Enumerator's #select
method to return just the monkeys from your collection. If you have your parsed YAML object in a variable called your_yaml
, this code would return what you are asking for:
your_yaml.select { |item|item['monkey'] }
您可能不需要第二级中的连字符.如果你改变这个...
You probably don't need the hyphens in the second level. If you change this...
- monkey:
- name: Chee-Chee
- age: 2
进入这个:
- monkey:
name: Chee-Chee
age: 2
猴子的属性将是一个散列,而不是一个散列数组.我想这对你更有用.
The monkey's properties will be a hash, instead of an array of hashes. I'd imagine this is more useful to you.
这篇关于Ruby 中的 YAML 解析:如何仅获取某种类型的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!