From: Josh Cheek Date: 2010-12-06T20:43:38+09:00 Subject: Re: Traverse YAML node tree with non-unique values --0016363104e914cf9f0496bc4c1f Content-Type: text/plain; charset=ISO-8859-1 On Mon, Dec 6, 2010 at 4:43 AM, Martin C. wrote: > I have a YAML document which I believe is valid (at least it would be > representable in XML): > > purchase_order: > date: 10/12/2010 > vendor: 12345 > item: > product: Tomatoes > quantity: 5 > item: > product: Eggs > quantity: 2 > > The problem is that using YAML.read on this produces a Hash in which > only one item occurs because (naturally) it has to be unique. > > How can one traverse the nodes in a YAML document like this? > > -- > Posted via http://www.ruby-forum.com/. > > Rather than having multiple keys that are the same (which doesn't work since this is a hash data structure), you instead use an Array. I find an easier way to figure out how things should look it is to go from data that you want (what should it look like after being read), then dump it, and examine the results. data = { :purchase_order => { :date => '10/12/2010' , :vendor => 12345, :items => [{ :product => 'Tomatoes', :quantity => 5, },{ :product => 'Eggs', :quantity => 2, }] } } require 'yaml' result = YAML.dump(data) puts result puts require 'pp' pp YAML.load(result) # >> --- # >> :purchase_order: # >> :date: 10/12/2010 # >> :vendor: 12345 # >> :items: # >> - :product: Tomatoes # >> :quantity: 5 # >> - :product: Eggs # >> :quantity: 2 # >> # >> {:purchase_order=> # >> {:date=>"10/12/2010", # >> :vendor=>12345, # >> :items=> # >> [{:product=>"Tomatoes", :quantity=>5}, {:product=>"Eggs", :quantity=>2}]}} --0016363104e914cf9f0496bc4c1f--