From: Mike Stok Date: 2002-09-11T03:35:05+09:00 Subject: Re: Multi-level sort idiom? In article <1031682194.811634@cswreg.cos.agilent.com>, Brett Williams wrote: > Let's say I have an array, each element of which is a 2-dimensional array > of ints. > > I want to sort with the first element in the 2D array taking precedence, > but using the second as a tiebreaker. > > So far, I haven't come up with a nice idiom that doesn't seem a bit kludgy: > What I tried was to do something like: > x.sort {|a,b| a[0]<=>b[0] || a[1]<=>b[1]} > but 0 is not false in Ruby so this doesn't work. > > x.sort {|a,b| 2*(a[0]<=>b[0]) + (a[1]<=>b[1])} > works, but is non-intuitive and not pretty. > > Does anyone have a nice clean rubyesque idiom for this? You can use Numeric's nonzero? e.g. x = [[5, 1], [3, 2], [3, 3], [1, 5]] x.sort { |a, b| (a[0] <=> b[0]).nonzero? || a[1] <=> b[1] } => [[1, 5], [3, 2], [3, 3], [5, 1]] Hope this helps, Mike -- mike@stok.co.uk | The "`Stok' disclaimers" apply. http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA mike@exegenix.com | Fingerprint 0570 71CD 6790 7C28 3D60 http://www.exegenix.com/ | 75D2 9EC4 C1C0 0599 13DA