Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse YAML into a hash/object?

Tags:

ruby

yaml

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

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

I'm using the following Ruby method to parse that YAML file into a set of objects 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, that method works, but I find it queer that I need to use item[1][:title] to access the attributes of the object I'm iterating over. How can I build my YAML file or my parsing code to allow me to use the more standard item[:title]?

like image 793
Kevin Whitaker Avatar asked May 01 '13 19:05

Kevin Whitaker


1 Answers

It's a Hash. The parse_yaml output is:

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

You may to use the each_value method like this:

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

Recomend: YAML for Ruby

like image 55
Ivan Black Avatar answered Sep 18 '22 22:09

Ivan Black