From: Brian Candler Date: 2004-10-10T00:47:11+09:00 Subject: Re: A sort_by descending sort On Sat, Oct 09, 2004 at 12:55:14AM +0900, Michael Gaunnac wrote: > # sort ascending descending year > descending month/day descending hour:minute > arr = arr.sort_by {|i| [[i.slice(0,1)], > [i.slice(7,4).tr('0-9','9876543210')], > [i.slice(1,5).tr('/0-9','/9876543210')], > [i.slice(11,5).tr(':0-9',':9876543210')]]} > > arr.each {|i| print i, "\n"} > > > > Can this sort be simplified (with Ruby of course)? > Arguably cheating, and very specific to this particular example, but: arr2 = arr.sort_by { |i| [-i[0], i[7..10], i[4..5], i[1..2], i[11..15]] }.reverse! For a more general pattern, how about: module Rev def <=>(other); -super; end end arr3 = arr.sort_by { |i| [i[0..0], i[7..10].extend(Rev), i[4..5].extend(Rev), i[1..2].extend(Rev), i[11..15].extend(Rev)] } or more compactly, arr4 = arr.sort_by { |i| [i[0], (i[7..10]+i[4..5]+i[1..2]+i[11..15]).extend(Rev)] } To be really cute, let's define 'negative strings': class String def -@ if kind_of? Rev String.new(self) else extend Rev end end end arr5 = arr.sort_by { |i| [i[0], -(i[7..10]+i[4..5]+i[1..2]+i[11..15])] } Regards, Brian.