From: Albert Wagner Date: 2002-09-13T08:47:54+09:00 Subject: Re: Multi-level sort idiom? On Tuesday 10 September 2002 01:35 pm, 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? Rubyesque idiom? Probably not, but this is readable: y = x.sort{|a,b| if (result = a[0]<=>b[0]) != 0 result else a[1]<=>b[1] end }