From: Dave Thomas Date: 2001-05-17T09:12:41+09:00 Subject: [ruby-talk:15320] Re: Pluggable sorting - How would you do it? Wayne Scott writes: > From: matz@zetabits.com (Yukihiro Matsumoto) > > It implements Schwartzian transformation inside. I like this idea, > > but am not yet sure "sort_by" is a proper name for the behavior. > > How about "sort_using" ?? > > BTW I have noticed that sorting on multiple fields feels clumsy in > Ruby. > > tbl.sort! do |a,b| > r = b[0] <=> a[0] > r = a[1] <=> b[1] unless r.nonzero? > r > end > > vs > > sort {$b->[0] <=> $a->[0] > || > $a->[1] <=> $b->[1]} @tbl; > > in perl. The example in http://www.rubycentral.com/book/ref_c_numeric.html#nonzero_qm shows a slightly more idiomatic form: tbl.sort {|a,b| (b[0] <=> a[0].nonzero? || b[1] <=> a[1] } This turns out to be exactly the same number of characters as the Perl version (give or take :) Of course, if tbl consists of 2 element arrays, you could also just write tbl.sort.reverse as Array#<=> does what you'd expect. Regards Dave