Gennady Bystritsky | 15 May 18:36

Re: Access Hash in the same order that was created

> -----Original Message-----
> From: mario <at> betware.com [mailto:mario <at> betware.com]
> Sent: Thursday, May 15, 2008 9:23 AM
> To: ruby-talk ML
> Subject: Access Hash in the same order that was created
>
> I need to access to a Hash in the same order that It was created:
>
> mh=Hash.new()
> mh["one"]="1"
> mh["two"]="2"
> mh["three"]="3"
> mh["four"]="4"
>
> mh.each {|val|
>   puts val[0]
> }
>
> In this example I get:
> three
> two
> one
> four
>
> and I would like to get:
> one
> two
> three
> four
>
>
> is that possible?

No way with standard Hash, and it shouldn't be really. You can use an array instead of a hash, and Array#assoc
to retrieve entries based on keys.

Gennady.

Gmane