On Wed, Feb 24, 2010 at 6:12 AM, Saeed Bhuta <saeed.bhuta / placr.co.uk> wrot=
e:
> Hi All,
>
> I am a beginner to Ruby. Currently I am working with Hashes and Arrays.
>
> I have a loop where the code saves several objects into a Hash.
> Everytime the loop is run the objects in the Hash are overwritten,
> therefore I append the objects into an Array so that data is not lost.
>
> #begining of loop ommitted
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0trainHash =3D {}
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0trainHash['order'] =3D tubeOrder
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0trainHash['destination'] =3D destination
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0trainHash['currentLocation'] =3D currentLo=
cation
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0trainHash['dueIn'] =3D dueInMinsValue
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0#trainHash['dueintimestamp'] =3D dueInTime=
stamp.to_s
>
> =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0trainArray << trainHash
> =A0 =A0 =A0 =A0 =A0 =A0 end
>
> From what I have read so far, Arrays are indexed by an integer with
> indexing starting at '0'.
>
> So for example, if the above loop was run twice; the number of objects
> in the trainArray would be two and referred using [0] for the first
> object and [1] for the second object.
>
> My question is, is it possible to refer the elements as they were stored
> in the Hash? For example, I want the code to return the value of the
> 'order' field in the second object in the trainArray.

Robert already answered this question.  I'd like to point out that
your code for building the hashes inserted into the array could be
simplified:

#begining of loop ommitted

     trainArray <<  { 'order' =3D> tubeOrder,  'destination' =3D>
destination,  'currentLocation' =3D> currentLocation,
                                      'dueIn' =3D> dueInMinsValue,
'dueintimestamp' =3D> dueInTimestamp.to_s}

   end

--=20
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale