From: Rick DeNatale Date: 2007-03-20T02:25:06+09:00 Subject: Re: Sorting Dates and Times in an array On 3/19/07, Paul wrote: > Hi there. I am having a bit of trouble trying to solve a particular > sorting problem with an array of data. > > Please bear with me for a moment regarding the setup of this problem. > I don't currently have any control over the input data. I am just > trying to format the report of this data as per the requirement. > > I have the following sample array data to work with: > @date_array = [['2/22/07','1:03 pm'],['3/9/07','10:45 pm'], > ['3/1/07','1:52 pm'],['3/13/07','2:00 pm'],['2/28/07','10:45 am'], > ['3/5/07','4:00 pm'],['2/14/07','5:00 pm'],['3/9/07','10:18 am'], > ['3/13/07','11:15 am']] > > (The actual array contains more data, but this is good enough to work > on this problem. BTW, date format = mm/dd/yy.) > > Requirement: > 1) Sort in descending order by Date (i.e. @date_array[x][0] ) > 2) Sort in ascending order by Time (i.e. @date_array[x][1] ) (Standard Library) objects are your friend. rick@frodo:/public/rubyscripts$ cat datesort.rb date_array = [['2/22/07','1:03 pm'],['3/9/07','10:45 pm'], ['3/1/07','1:52 pm'],['3/13/07','2:00 pm'],['2/28/07','10:45 am'], ['3/5/07','4:00 pm'],['2/14/07','5:00 pm'],['3/9/07','10:18 am'], ['3/13/07','11:15 am']] p date_array.sort do |a, b| ddiff = Date.parse(b[0],true) <=> Date.parse(a[0],true) ddiff == 0 ? Time.parse(a[0]) <=> Time.parse(b[0]) : ddiff end rick@frodo:/public/rubyscripts$ ruby datesort.rb [["2/14/07", "5:00 pm"], ["2/22/07", "1:03 pm"], ["2/28/07", "10:45 am"], ["3/1/07", "1:52 pm"], ["3/13/07", "11:15 am"], ["3/13/07", "2:00 pm"], ["3/5/07", "4:00 pm"], ["3/9/07", "10:18 am"], ["3/9/07", "10:45 pm"]] rick@frodo:/public/rubyscripts$ -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/ IPMS/USA Region 12 Coordinator http://ipmsr12.denhaven2.com/ Visit the Project Mercury Wiki Site http://www.mercuryspacecraft.com/