From: Mark Hubbart Date: 2004-10-09T01:36:51+09:00 Subject: Re: A sort_by descending sort On Sat, 9 Oct 2004 00:55:14 +0900, Michael Gaunnac wrote: > > > gabriele renzi wrote: > > Michael Gaunnac ha scritto: > > > >> Perhaps this has already been covered, but I discovered this idiom > >> for doing a descending sort using sort_by. > > > > why not: > > >> [1,2.0,6,23 ,546,421.1,,0.1].sort_by {|x| 1-x} > > => [546, 421.1, 23, 6, 2.0, 1, 0.1] > > > > Anyway, thankx for making me think of this :) > > More context: > > arr = %W{ > A10/04/200420:30 > A10/04/200405:00 > A10/04/200420:00 > A10/06/200405:00 > A10/07/200409:37 > A10/07/200419:00 > A10/07/200421:30 > E10/08/200404:00 > A10/08/200407:50 > A10/08/200405:15 > D10/08/200404:00 > A10/08/200305:00 > A10/08/200405:00 > A10/08/200403:55 > B10/08/200404:15 > A10/07/200419:30 > A10/07/200422:00 > B10/07/200405:00 > B10/08/200407:50 > A10/08/200407:50 > A10/08/200407:25 > C10/08/200404:00 > B10/08/200404:00 > A10/08/200404:45 > A10/08/200404:10 > B10/08/200404:10 > A10/08/200404:00 > } > # 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)? > assuming an unchanging format, perhaps: arr = arr.sort_by do |i| i.scan(/(.)(..).(..).(....)(..):(..)/).map do |a,*date| m,d,y,h,n = *date.map{|x| x.to_i} [a,-y,-m,-d,-h,-n] end end cheers, Mark