From: Brian Candler Date: 2004-10-08T23:32:22+09:00 Subject: Re: A sort_by descending sort On Fri, Oct 08, 2004 at 10:57:20PM +0900, Michael Gaunnac wrote: > Perhaps this has already been covered, but I discovered this idiom for doing a descending sort using sort_by. > > arr = Array.new > (0..20).each {|i| arr.push sprintf('%02d', i)} > p arr > #=>["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"] > > arr = arr.sort_by {|i| [i.slice(0,2).tr('0-9','9876543210')]} # descending sort using 9's complement > > p arr > #=>["20", "19", "18", "17", "16", "15", "14", "13", "12", "11", "10", "09", "08", "07", "06", "05", "04", "03", "02", "01", "00"] arr2 = arr1.sort.reverse! or arr2 = arr1.sort_by { |i| ... }.reverse! I'd guess that would be quicker and less memory-hungry than generating temporary string objects with translated characters in them. Regards, Brian.