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]
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With