William James
10/30/2008 5:03:00 PM
On Oct 30, 10:00 am, Brian Candler <b.cand...@pobox.com> wrote:
> Josef 'Jupp' Schugt wrote:
> > def datecmp(a, b, reasonable = true)
> > arra, arrb = a.split('/'), b.split('/')
> > cmp = (arra[2] <=> arrb[2])
> > return cmp if (cmp = (arra[2] <=> arrb[2])) != 0
> > if reasonable
> > (cmp = (arra[0] <=> arrb[0])) != 0 ? cmp : (arra[1] <=> arrb[1])
> > else
> > (cmp = (arra[1] <=> arrb[1])) != 0 ? cmp : (arra[0] <=> arrb[0])
> > end
> > end
>
> > date = ['12/01/2007', '11/02/2007', '11/11/2005']
> > puts "reasonable date format"
> > puts date.sort { |a, b| datecmp(a, b) }
> > puts "\nno reasonable date format"
> > puts date.sort { |a, b| datecmp(a, b, false) }
>
> I think you got "reasonable" and "unreasonable" reversed (unless you are
> American :-)
>
> Here is a shorter solution:
>
> MapR = lambda { |x| x.split('/').values_at(2,1,0) }
> MapU = lambda { |x| x.split('/').values_at(2,0,1) }
>
> date = ['12/01/2007', '11/02/2007', '11/11/2005']
> puts "reasonable date format"
> puts date.sort_by(&MapR)
> puts "\nno reasonable date format"
> puts date.sort_by(&MapU)
MAP_R = proc{|x| x.split('/').reverse }
MAP_U = proc{|x| y=x.split('/'); [y.pop,y] }
dates = %w(12/01/2007 11/02/2007 11/11/2005)
puts "reasonable date format"
puts dates.sort_by(&MAP_R)
puts "unreasonable date format"
puts dates.sort_by(&MAP_U)