From: GOTO Kentaro Date: 2002-09-13T09:56:25+09:00 Subject: Re: Multi-level sort idiom? At Fri, 13 Sep 2002 09:21:37 +0900, Mike Stok wrote: > The result of nonzero? does get returned, effectively nonzero? > transforms any number except 0 to itself, and 0 is transformed to a > false value, nil. Historically, nonzero? was introduced for very this kind of sort (what is the correct name?). But Array#<=> was introduced in no time after nonzero? was. Tadayoshi Funaba, who is the inventor of nonzero? and Array#<=>, said that that Array#<=> might obsolets nonzero?. He thought that a user however could choose favorite one [ruby-list:8546]. I prefer Array#<=> way. In 1.7.x, we can do x.sort_by{|a| [a[1],a[2],a[0]]} instead of x.sort{|a,b| [a[1],a[2],a[0]] <=> [b[1],b[2],b[0]]} and the former is faster than the latter because sort_by implements Schwartzian transform(*1) in C. sort_by in Ruby is defined in shim(*2) for 1.6.x as follows: module Enumerable def sort_by ary = map { |i| [yield(i), i] } ary.sort! { |a, b| a[0] <=> b[0] } ary.map! { |i| i[1] } end end (*1) http://www.5sigma.com/perl/schwtr.html (*2) http://www.ruby-lang.org/~knu/cgi-bin/cvsweb.cgi/shim/ruby16/lib/features/ruby18/enumerable.rb -- Gotoken