On Tue, 4 Apr 2006, Martin Boese wrote:

> Hello,
>
> I am building a menu structure for rails that I'd like to store in a simple
> Hash.
>
> Now I found out that ruby Hashes do not keep the order, like this program:
>
>> b = {'upkpgn'=>1,
>>      'jmay'=>2,
>>      'vkvxxm'=>3}
>>
>> b.each_key {|k|
>>  puts "%s => %s" % [k, b[k]]
>> }
>
> ...will output:
>
>> upkpgn => 1
>> vkvxxm => 3
>> jmay => 2
>
> (vkvxxm and jmay are swapped)
>
> I read an article describing this behavior, but it only mentions a 'sort'
> solution which is useless for me because my menu has a logical order:
>
> http://www.ruby-talk.org/cgi-bin/scat.rb/ruby/ruby-talk/159776
>
> Are there any workarounds for this? Or shall I rather write my own containers?

use an Array and Array#assoc

     harp:~ > cat a.rb
     b =
       %w( upkpgn 1 ),
       %w( jmay 2 ),
       %w( vkvxxm 3 )

     b.each{|kv| puts "%s => %s" % kv}

     puts b.assoc('upkpgn').last
     puts b.assoc('jmay').last
     puts b.assoc('vkvxxm').last


     harp:~ > ruby a.rb
     upkpgn => 1
     jmay => 2
     vkvxxm => 3
     1
     2
     3


> BTW: Why is ruby doing this anyways...?!

hashes are, by definition, unsorted containers.

regards.

-a
-- 
share your knowledge.  it's a way to achieve immortality.
- h.h. the 14th dali lama