From: Martin Stannard Date: 2002-10-11T09:12:13+09:00 Subject: Sorting an array of hashes Hi, I've an array of hashes I want to sort, first by key1 and then subsort by key2. I've some code that works but was wondering if there is a more idiomatic method of doing this in Ruby: # create an array of Hashes. We want to sort by firstKey, then secondKey. unsorted = [] 100.times do |t| unsorted.push({ "firstKey" => rand(10), "secondKey" => t}) end # get an array of unique firstKeys firstKeys = [] unsorted.each { |hash| firstKeys.push(hash["firstKey"]) } firstKeys.uniq!.sort! finalArray = [] firstKeys.each do |aKey| # find all the items of aKey firstKeyMatches = unsorted.find_all { |hash| hash["firstKey"] == aKey} # sort them and add to the finalArray finalArray += firstKeyMatches.sort {|x,y| x["secondKey"] <=> y["secondKey"] } end # the result finalArray.each { |hash| puts "firstKey [#{hash["firstKey"].to_s.rjust(4)}] secondKey [#{hash["secondKey"].to_s.rjust(4)}]" } =================== regards, Martin