How to parse YAML into a hash / object?

I have a YAML file with several entries that look like this:

001: :title: Some title :description: Some body text maybe 002: :title: Some title :description: Some body text maybe 

I use the following Ruby method to parse this YAML file into a set of objects that I can iterate over:

 def parse_yaml(file) YAML::load(File.open(File.join(settings.yaml_folder, file))) end def use_yaml @items = parse_yaml('items.yml') @items.each do |item| x = item[1][:title] etc... end end 

Now this method works, but it seems strange to me that I need to use item[1][:title] to access the attributes of the object that I iterate. How can I create my YAML file or my syntax code to allow me to use the more standard item[:title] ?

+7
source share
3 answers

This is a hash. Output parse_yaml :

 { 1=> { :title=>"Some title", :description=>"Some body text maybe"}, 2=> { :title=>"Some title", :description=>"Some body text maybe" } } 

You can use each_value method as follows:

 #... @items = parse_yaml('items.yml') @items.each_value do |item| x = item[:title] # ... etc end 

Recommendation: YAML for Ruby

+8
source

The main problem is that your YAML file stores your data as a hash and tries to access it as an array.

To convert your data to an array format:

 --- - :title: Some title :description: Some body text maybe - :title: Some title :description: Some body text maybe 

It is also interesting to note that you had to use item[1][:title] to link to your items, so the keys 001 and 002 converted to integers by YAML.load.

You can confirm this in irb:

 irb(main):015:0> YAML.load(File.open("./test.yml")) => {1=>{:title=>"Some title", :description=>"Some body text maybe"}, 2=>{:title=>"Some title", :description=>"Some body text maybe"}} 
+3
source

Your YAML is a hash serialization so you can:

 @items.each do |key, item| #do something with item[:title] end 

Or change your YAML to look like this:

 - :title: blah :description: description - :title: second title :description: second description 

This will return a YAML.load array.

+1
source

All Articles