You should renew rmcategory every time.

So, the following code will work as you think.

roomcats =3D Array.new
doc.xpath('//RoomCategory').each do |rc|
 rmcategory =3D 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
<purvez / nexar.free-online.co.uk> wrote:
> I'm parsing an XML document and trying to create an array of hashes
> using the following:
>
> roomcats =3D Array.new
> rmcategory =3D Hash.new
> doc.xpath('//RoomCategory').each do |rc|
> =A0rmcategory["id"]=3Drc['Id']
> =A0rmcategory['sdesc']=3Drc.xpath('./Description').text
> =A0rmcategory['ldesc']=3D rc.xpath('./RoomDescription').text
>
> =A0roomcats.push rmcategory
> end
>
> However what I'm getting is an array of hashes with all elements of the
> array equal to the last element. =A0A 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
>
> --
> Posted via http://www.ruby-forum.com/.
>
>



--=20
Haruka YAGNI
hyagni / gmail.com