From: William James Date: 2006-07-30T02:40:06+09:00 Subject: Re: Hash order bug? Charles Hoffman wrote: > I think this is just a common mistake among newbie-ish programmers. > Which isn't to say anything about Javier specifically, I don't know him, > but in general, a review of one's Data Structures course may be in order > when this happens. But I think it happens to just about every > programmer at some point. I remember the first time I tried to do some > ASP scripting for some web pages and I decided to use the Dictionary > object. At one point I wanted to loop through the Dictionary and > display a listing of its contents. I got all pissed off when I realized > that the loop didn't return the items in alphabetical order. Only later > did I realize that the underlying data structure is a hash, and that the > whole point of a hash is to maximize speed of access by sacrificing > things like, being able to iterate it in any particular order. Of > course, the word "Dictionary" does, for most of us, bring to mind > something that's in alphabetical order, so maybe it was Microsoft's > fault for givig it a dumb name. At any rate, it would be a bad idea to > allow what is essentially a mistake made by programmers to force an > abnormal, slower implementation onto a data structure whose definition > is largely agreed upon in computing. In other words, I'm with the "we > don't need an 'ordered hash'" crowd. I think that, besides slowing it > down, it goes against the very definition of what a hash is. True. > > If you need to iterate through a hash in order by key, it's a simple > matter to grab an array of the keys first, sort it, then iterate from > that. I'm probably going to embarrass myself with my Ruby nuby-ness > here, but off the top of my head: > > my_hash.keys.sort.each{|key| doSomethingWith(my_hash[key])} h = { 'zebra', 2, 'horse', 0, 'sheep', 1 } ==>{"horse"=>0, "sheep"=>1, "zebra"=>2} h.sort.each{|x| p x} ["horse", 0] ["sheep", 1] ["zebra", 2] ==>[["horse", 0], ["sheep", 1], ["zebra", 2]]