Martin Stannard <martin / massive.com.au> writes:

> 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
> 
<code snipped>

a shorter one (not tested)

#create a hash of firstKey containing array of k2
top={}
unsorted.each{|k1, k2|
        if top[k1]
                top[k1] << k2
        else
                top[k1] = [k2]
        end
}
sorted = []
top.sort.each{|k1, ak2|
        ak2.sort.each {|k2|
                sorted << [k1, k2]
        }
}
p sorted
 

YS.