Hash table order

Why:

a = {}
=> {}
a[“HEAD”] = “ASD”
=> “ASD”
a[“TABLE_HEAD”] = “SKSKJKDKSKKSDJKSKDJSKJDKS SKDJSKDJS”
=> “SKSKJKDKSKKSDJKSKDJSKJDKS SKDJSKDJS”
a[“LONG_TABLE_HEAD”] = “.zx,cmvn;alksdjf a.s,dmnf;ioxcvuaw.,.mnsdfl;k”
=> “.zx,cmvn;alksdjf a.s,dmnf;ioxcvuaw.,.mnsdfl;k”
a
=> {“HEAD”=>“ASD”, “LONG_TABLE_HEAD”=>“.zx,cmvn;alksdjf
a.s,dmnf;ioxcvuaw.,.mnsdfl;k”, “TABLE_HEAD”=>“SKSKJKDKSKKSDJKSKDJSKJDKS
SKDJSKDJS”}

I think ‘a’ should be:

{“HEAD”=>…, “TABLE_HEAD”=>…, “LONG_TABLE_HEAD”=> … }

NOT:

{“HEAD”=>…, “LONG_TABLE_HEAD”=> …, “TABLE_HEAD”=>… }

I don’t understand why Ruby puts third element into second position of my
hashtable.

···


Szymon Drejewicz

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:

=> {“HEAD”=>“ASD”, “LONG_TABLE_HEAD”=>“.zx,cmvn;alksdjf
a.s,dmnf;ioxcvuaw.,.mnsdfl;k”, “TABLE_HEAD”=>“SKSKJKDKSKKSDJKSKDJSKJDKS
SKDJSKDJS”}

“Szymon Drejewicz” drejewic@wsisiz.edu.pl schrieb im Newsbeitrag
news:b70os3$cv3$1@portraits.wsisiz.edu.pl…

Why:

a = {}
=> {}
a[“HEAD”] = “ASD”
=> “ASD”
a[“TABLE_HEAD”] = “SKSKJKDKSKKSDJKSKDJSKJDKS SKDJSKDJS”
=> “SKSKJKDKSKKSDJKSKDJSKJDKS SKDJSKDJS”
a[“LONG_TABLE_HEAD”] = “.zx,cmvn;alksdjf a.s,dmnf;ioxcvuaw.,.mnsdfl;k”
=> “.zx,cmvn;alksdjf a.s,dmnf;ioxcvuaw.,.mnsdfl;k”
a
=> {“HEAD”=>“ASD”, “LONG_TABLE_HEAD”=>“.zx,cmvn;alksdjf
a.s,dmnf;ioxcvuaw.,.mnsdfl;k”, “TABLE_HEAD”=>“SKSKJKDKSKKSDJKSKDJSKJDKS
SKDJSKDJS”}

I think ‘a’ should be:

{“HEAD”=>…, “TABLE_HEAD”=>…, “LONG_TABLE_HEAD”=> … }

NOT:

{“HEAD”=>…, “LONG_TABLE_HEAD”=> …, “TABLE_HEAD”=>… }

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.

Regards

robert