From: Robert Klemme Date: 2004-03-03T19:59:45+09:00 Subject: Re: why are Hashes so unsorted? what's your solution? "Ruby Baby" schrieb im Newsbeitrag news:20040303052244.GA89378@mail.hitmedia.com... > I try to avoid questions like "Why doesn't Ruby do what ___ does?" > > But I'm stumped by hashes and asking for help to find a new solution. > > 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? That's due to the nature of hashing. I suggest you get yourself a copy of an "data structures and algorithms" book (or find some online). The simplest explanation is that a hash is an array and entries are found using the #hash value of a key item by calulating that hash modulo the array size. That way keys don't necessarily appear in order. Assuming an array size of 10: irb(main):009:0> 1.step(100,7){|i| printf "hash=%3d index=%3d\n", i, i % 10} hash= 1 index= 1 hash= 8 index= 8 hash= 15 index= 5 hash= 22 index= 2 hash= 29 index= 9 hash= 36 index= 6 hash= 43 index= 3 hash= 50 index= 0 hash= 57 index= 7 hash= 64 index= 4 hash= 71 index= 1 hash= 78 index= 8 hash= 85 index= 5 hash= 92 index= 2 hash= 99 index= 9 => 1 Of course this is simplistic and real hash implementations are more complex, i.e. you need resizing and deal with collisions (hash 22 and hash 92, as well as multiple keys having the same hash value) etc. > And what do you think is the Ruby way solution for what I need to do? Don't use a method that returns the query result as hash. The simplest thing would be to return an array of arrays. Using a tree or any other sorted associative container is only appropriate if you really need key based accesses. But if you just want to present what the db returns then array is the way to go since it preserves insertion order. Regards robert