From: David Garamond Date: 2004-03-03T19:42:35+09:00 Subject: Re: why are Hashes so unsorted? what's your solution? Ruby Baby wrote: > I use MySQL databases a lot. Let's say I have a query to find the > top-selling albums in my store: > > 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. > > In Ruby, it's an unordered jumble. > Why is that? Most language don't guarantee insert order for hash, in fact IIRC some deliberately randomize it. It's faster and in some cases needed for security reasons. So I guess PHP is the minority here (plus I still hate the fact that they merge the concept of array and hash, WTF with that?) > And what do you think is the Ruby way solution for what I need to do? records = { "sku1" => ["artist1","title1",100], "sku2" => ["artist2","title2",200], "sku3" => ["artist3","title3",300], "sku4" => ["artist4","title4",400], "sku5" => ["artist5","title5",500], } records.keys.sort.each {|k| record = records[k] # do stuff with record... } Or you can make a Hash that maintains insert order. I think there is one at RAA (http://www.ruby-lang.org/en/raa.html). -- dave