Ross Bamford
1/15/2006 12:37:00 PM
On Sun, 15 Jan 2006 02:30:12 -0000, thila thila <isputnik_98@yahoo.com>
wrote:
> Guys-
> I am trying to create an YAML file like the following:
> 3
> --- Begin
> ga:
> name: Georgia
> capital: savanah
> population: 1 mil
> cities:
> city:
> name: Atlanta
> zip: 30328
> city:
> name: Savanah
> zip: 30304
>
>> [.. snip ..]
>
> #---End
>
> I keep getting "parse" error while loading it to yaml. Even if I manage
> to load with "-", I could never fetch the City and zip details. Can
> anyone help me with this nested yaml file? thanks
>
Firstly, I'm not sure whether you added the ---Begin and ---End to post
this here? If not, please remove them (replace the first one with just
'---' but it's not required with this input I think). If that doesn't
work, you should probably post the error you're seeing - removing those
two lines made it parse just fine here.
Secondly, there seem to be a few oddities in your data? The 'cities' hash
will only contain 'Savanah' in this case - using the same hash key twice
results in overwriting the previous data. I don't know what you're aiming
for, but one way to overcome that might be:
---
tx:
name: Texas
capital: Dallas
population: 2 mil
cities:
Fortworth:
zip: 22222
Dallas:
zip: 12345
This (slightly abridged) IRB session shows it in use (with basic hash
access only).
$ irb -ryaml -rpp --prompt xmp
states = YAML.load(File.read('states.yaml'))
pp states
{"tx"=>
{"name"=>"Texas",
"cities"=>{"Dallas"=>{"zip"=>12345}, "Fortworth"=>{"zip"=>22222}},
"population"=>"2 mil",
"capital"=>"Dallas"},
"ga"=>
{"name"=>"Georgia",
"cities"=>{"Atlanta"=>{"zip"=>30328}, "Savanah"=>{"zip"=>30304}},
"population"=>"1 mil",
"capital"=>"Savanah"}}
# => nil
states['tx']['population']
# => 2 mil
states['tx']['cities']['Dallas']['zip']
# => 12345
states['tx']['cities']
# => {"Dallas"=>{"zip"=>12345}, "Forthworth"=>{"zip"=>22222}}
states['tx']['cities'][states['tx']['capital']]
# => {"zip"=>12345}
Cheers,
--
Ross Bamford - rosco@roscopeco.remove.co.uk