Forum: Ruby On Hashes - How the hashes printing works?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Neela megha shyam C. (Guest)
on 2009-05-27 12:16
Hi All,

I have my code as follows:-

people = {
"torvalds"=>{"lname"=>"Torvalds", "fname"=>"Linus",
"job"=>"maintainer"},  "matsumoto"=>{"lname"=>"Matsumoto",
"fname"=>"Yukihiro", "job"=>"Ruby originator"},
"litt"=>{"lname"=>"Litt", "fname"=>"Steve", "job"=>"troubleshooter"}
}
keys = people.keys
for key in 0...keys.length
print "key  : ", keys[key], "\n"
print "lname: ", people[keys[key]]["lname"], "\n"
print "fname: ", people[keys[key]]["fname"], "\n"
print "job  : ", people[keys[key]]["job"], "\n"
print "\n\n"
end

O/p:-
key  : litt
lname: Litt
fname: Steve
job  : troubleshooter
key  : matsumoto
lname: Matsumoto
fname: Yukihiro
job  : Ruby originator
key  : torvalds
lname: Torvalds
fname: Linus
job  : maintainer

Question:-
Why key of "litt" is printed first thought the first key of hash is
"torvalds"?

Thanks and regards,
Neela.
Markus S. (Guest)
on 2009-05-27 12:26
(Received via mailing list)
Hashes enumeration does not mirror insertion order.
Hashes are not ordered:

http://en.wikipedia.org/wiki/Hash_table#Drawbacks

Markus
Neela megha shyam C. (Guest)
on 2009-05-27 12:28
Markus S. wrote:
> Hashes enumeration does not mirror insertion order.
> Hashes are not ordered:
>
> http://en.wikipedia.org/wiki/Hash_table#Drawbacks
>
> Markus

Thank you Markus.
Jarmo P. (Guest)
on 2009-05-28 10:30
Jou could use orderedhash gem to have hashes ordered like arrays for
example if you really need it for some reason:
http://codeforpeople.com/lib/ruby/orderedhash/

Markus S. wrote:
> Hashes enumeration does not mirror insertion order.
> Hashes are not ordered:
>
> http://en.wikipedia.org/wiki/Hash_table#Drawbacks
>
> Markus
Markus S. (Guest)
on 2009-05-28 14:57
(Received via mailing list)
Or maintain an "order of insertion key array".
This topic is locked and can not be replied to.