Hashes are unordered, by definition. A hash works by dividing the keys into
“buckets”, where each key is passed through a hashing function, and all keys
with the same hash function result end up in the same bucket. So traversing
the hash (with ‘each’, for example) will give you an element ordering which
depends on their hash values, not strictly in the order in which they were
inserted.
If you need the order preserving then use an array.
Regards,
Brian.
···
On Wed, Apr 09, 2003 at 06:38:36PM +0900, Szymon Drejewicz wrote:
I don’t understand why Ruby puts third element into second position of my
hashtable.
First, keys are not sorted. Especially there is no ordering according to
insertion.
Second the order {“HEAD”=>…, “LONG_TABLE_HEAD”=> …, “TABLE_HEAD”=>… }
corresponds to the lexical ordering of these key strings. If you need
sorted access, do
h.keys.sort.each {|key| puts “#{key}=>#{h[key]}” } so something similar.
If you want to order by length you need to define your own ordering:
h.keys.sort {|a,b|a.length<=>b.length}.each {|key| puts
“#{key}=>#{h[key]}” }
or something similar.