Javier Valencia wrote:
> Hi --
>
>
>> I have this piece of simple code:
>>
>> ----------------------------------------------
>> def foo
>> return 5
>> end
>>
>> a = {:gr => false, :und => false, :det => true, :sta => false, :inv
>> => false}
>> puts a.inspect
>> ----------------------------------------------
>>
>> when I execute it i get a totally unordered hash:
>>
>> ----------------------------------------------
>> ruby pro.rb
>> {:inv=>false, :gr=>false, :und=>false, :det=>true, :sta=>false}
>> ----------------------------------------------
>>
>> Now, i delete the foo function from the code (the foo function don't
>> do nothing at all), and i get a well ordered hash:
>>
>> ----------------------------------------------
>> ruby pro.rb
>> {:gr=>false, :und=>false, :det=>true, :sta=>false, :inv=>false}
>> ----------------------------------------------
>>
>>
>> What's happening? all my code is behaving wrong because of that.
>
>
> Hashes are unordered. If you need an ordered collection, you'll need
> to use an array.
>
>
> David
>
Oh my god, i didn't know it, sorry. Is that a missing feature?
No. What language has ordered hashes?
When you say
a = {:gr => false, :und => false, :det => true, :sta => false, :inv
=> false}
you are saying that you want to access the values in this fashion:
a[:und]
So the order in which they are stored is irrelevant.
If you want to access them this way
a[1]
then you set them up like this
[ false, false, true, false, false ]
If you want to get a sequence of values in a certain order:
a.values_at( :und, :det, :sta )
If you want to have your cake and eat it too, you could
use an association list:
as = [[:foo,22], [:bar,33], [:baz,44]]
=> [[:foo, 22], [:bar, 33], [:baz, 44]]
as.assoc(:bar)
=> [:bar, 33]
as.rassoc( 44 )
=> [:baz, 44]
as[0]
=> [:foo, 22]
If the list has a large number of elements, access will be slow.
···
dblack@wobblini.net wrote:
> On Tue, 25 Jul 2006, Javier Valencia wrote: