Nicolas Raoul Nicolas Raoul - 6 months ago 18
Ruby Question

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

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
, but what is the syntax with YAML/Ruby ?

Note: I don't want to create a
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: { |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.