From: daz Date: 2004-03-03T15:44:45+09:00 Subject: Re: why are Hashes so unsorted? what's your solution? "Ruby Baby" wrote: > I try to avoid questions like "Why doesn't Ruby do what ___ does?" Go on, force yourself ;) > > SELECT sku, artistname, albumtitle, sold FROM albums > ORDER BY sold DESC LIMIT 20; > > When I get the hash of results from the database, I'm used to making > the "sku" the hash key since it's the only unique identifier. > A perfect hash key. Used everywhere by my iteration methods. > > In PHP, this is no problem. I get the hash, and I can do the > "each" iteration on it, and get my top-selling albums in order. > Sounds to me that you get an ordered hash - a special form of hash. > In Ruby, it's an unordered jumble. That's a hash; across the universe. > Why is that? The answer to that would probably irritate you more than is necessary; but, in short, because it's a Hash. > > And what do you think is the Ruby way solution for what I need to do? > > > (The simple query I gave above was much simpler, but I have lots and > lots of MySQL queries where I want the results to come back in the > order that MySQL gave them, but with full access to the hash results.) > You've ruled out one option; of omitting the ORDER BY clause then using Enumerable#sort_by on the hash before iterating -- so I won't bring that up. > Thanks! I'm not done, yet. Or you could use a container which maintains its order - the Array which, in your case, might be an array of hashes. [{:sku => 10, :artist=>'Global Communication', :albumtitle => 'Pentamerous Metamorphosis'}, {:sku => 54, :artist=>'Eat Static', :albumtitle => 'Abduction'}, {...} ] There'll be other ways, I'm sure ;) daz