From: John W Higgins Date: 2009-10-31T02:17:22+09:00 Subject: Re: two stage array sorting --0016368e2fe802a08d04772a2e93 Content-Type: text/plain; charset=ISO-8859-1 Morning Tim, On Fri, Oct 30, 2009 at 9:35 AM, Tim Ferrell wrote: > > I have an array of strings like so: > > Tuesday 12:00 AM > Sunday 9:00 AM > Tuesday 3:00 PM > Friday 7:30 AM > Wednesday 5:00 PM > > and I want the array sorted by day name and then time. Is it possible to > do this without resorting to a two stage process? Currently I am > breaking the array out into arrays by day and sorting those by time and > then reassembling... it just feels dirty :-) > > require 'date' def sort_datetime_array(ary) fmt = '%A %I:%M %p' ary.sort{ |a,b| DateTime.strptime(a, fmt) <=> DateTime.strptime(b, fmt) } end c = ['Friday 1:00 PM', 'Tuesday 12:00 AM', 'Wednesday 3:00 PM', 'Tuesday 11:59 PM'] puts sort_datetime_array(c) --output-- Tuesday 12:00 AM Tuesday 11:59 PM Wednesday 3:00 PM Friday 1:00 PM Just note that the original array is not sorted in this case - the method returns a new sorted array - if you wanted the sorting done in place then change sort to sort! in the method John --0016368e2fe802a08d04772a2e93--