From: gabriele renzi Date: 2004-10-09T01:14:49+09:00 Subject: Re: A sort_by descending sort Michael Gaunnac ha scritto: > 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)? > ah, I see :) well, you can remove 6 [] 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')]} then readd them in defferent places: arr = arr.sort_by {|i| [i[0,1], i[7,4].tr('0-9','9876543210'), i[1,5].tr('/0-9','/9876543210'), i[11,5].tr(':0-9',':9876543210')]} but I guess I'd just use sort +reverse, and I'm not good at golf :/