Hi --

On Fri, 11 Oct 2002, Martin Stannard wrote:

> 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:

One way would be:

  unsorted = (0...100).map {|t| { :k1 => rand(10), :k2 => t} }
  sorted = unsorted.sort do |a,b|
    if (n = a[:k1] <=> b[:k1]).zero?
      a[:k2] <=> b[:k2]
    else
      n
    end
  end

or, if you don't have my probably ridiculous aversion to the ternary
operator:

  unsorted = (0...100).map {|t| { :k1 => rand(10), :k2 => t} }
  sorted = unsorted.sort do |a,b|
    (n = a[:k1] <=> b[:k1]).zero? ? a[:k2] <=> b[:k2] : n
  end


David

-- 
David Alan Black                      | Register for RubyConf 2002!
home: dblack / candle.superlink.net     | November 1-3
work: blackdav / shu.edu                | Seattle, WA, USA
Web:  http://pirate.shu.edu/~blackdav | http://www.rubyconf.com