Sorting arrays and hashes in Ruby
Archive - Originally posted on "The Horse's Mouth" - 2010-01-30 21:23:36 - Graham EllisIn Ruby, you can use the sort method on an array to sort that array - but you cannot sort a hash. That's because of the techniques used within a hash to make it very fast to look up individual elements.
So what do you do if you want to sort something like this: ?
stuff = {"Steve" => "Kent", "Graham" => "Wiltshire",
"Chris" => "Wiltshire", "Betty" => "Windsor",
"Fred" => "Aberstwyth", "Harry" => "Potteries",
"Sarah" => "Wiltshire"}
You get an array of the keys (using the keys method on the hash), and then you sort the list. To output the pairs from the hash in order, you step through the hash in the order given in the list and the job is done!
There's an example [here] in the examples directory - a piece of code I wrote as a demonstration during this week's Ruby Programming Training Course.