Trying to create an array of hashes

I’m parsing an XML document and trying to create an array of hashes
using the following:

roomcats = Array.new
rmcategory = Hash.new
doc.xpath(’//RoomCategory’).each do |rc|
rmcategory[“id”]=rc[‘Id’]
rmcategory[‘sdesc’]=rc.xpath(’./Description’).text
rmcategory[‘ldesc’]= rc.xpath(’./RoomDescription’).text

roomcats.push rmcategory
end

However what I’m getting is an array of hashes with all elements of the
array equal to the last element. A bit of experimenting has shown that
each time the hash value changes through the loop the associated entry
in the Array is also changed. i.e. The array element is ‘pointing’ to
the hash rather than taking on separate values.

Please can someone tell me what I should do to achieve what I want.

Thanks

Purvez

You should renew rmcategory every time.

So, the following code will work as you think.

roomcats = Array.new
doc.xpath(’//RoomCategory’).each do |rc|
rmcategory = Hash.new
:
roomcats.push rmcategory
end

With your original version, all Hash objects in array refer to the
same object, and this cause the problem.

On Wed, Mar 30, 2011 at 4:20 PM, Purvez Desai

Haruka a million thanks. So simple… when you know how.

Very nicely explained.

Purvez

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs