On Apr 4, 2006, at 7:43 AM, 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) b.keys.sort.each { |k| # ... } > 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? You've mentioned the first one, you can sort when you access the values. You could also switch away from a Hash and use something like an Array of Arrays. Lookup the method Array#assoc and Array#rassoc, which might be helpful with this. > Or shall I rather write my own containers? I'm pretty sure there is an OrderedHash on the RAA. > BTW: Why is ruby doing this anyways...?! A Hash is, by definition, an unordered construct. James Edward Gray II