开发者

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

I have the following YAML:

- name: List of monkeys
- author: Nicolas Raoul
- version: 1
- monkey: Chee-Chee
- monkey: Curious George
- monkey: Mojo

How to get the array of monkeys in Ruby? The number of metadata pa开发者_C百科rameters (name, author, ...) is variable.

It would return something like [Chee-Chee, Curious George, Mojo]

Note: I don't want to create a monkeys node containing all monkeys as sub-items, because there are many monkeys and I want to keep the file really simple.


Well your YAML looks a little crazy: each of those lines is a hash containing one element. Still, if you're stuck with it, something like this would get you an array of monkey names:

require 'yaml'

data = YAML.load(DATA.read)
p data.map { |row| row['monkey'] }.compact

__END__
- name: List of monkeys
- author: Nicolas Raoul
- version: 1
- monkey: Chee-Chee
- monkey: Curious George
- monkey: Mojo

Obviously you could load the YAML from anywhere, it doesn't have to be in your DATA block.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜