开发者

YAML parsing in Ruby: How to get only a certain type of elements?

开发者 https://www.devze.com 2023-03-17 12:49 出处:网络
I have the following YAML: - name: List of monkeys - author: Nicolas Raoul - version: 2 - monkey: - name: Chee-Chee

I have the following 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

In Ruby, how to get the monkeys?

The number of metadata parameters in 开发者_如何学运维the preamble (name, author, ...) is variable.

It would return something like:

[{"monkey"=>[{"name"=>"Chee-Chee"}, {"age"=>2}]}, {"monkey"=>[{"name"=>"Curious George"}, {"age"=>6}, {"food"=>"bananas"}]}, {"monkey"=>[{"name"=>"Mojo"}, {"food"=>"peanuts"}]}]

In XML/XPath I would simply write /monkey, but what is the syntax with YAML/Ruby ?

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.


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

Into this:

- 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消