From: Siep Korteling Date: 2009-10-31T07:59:14+09:00 Subject: Re: two stage array sorting John W Higgins wrote: > Morning Tim, > > On Fri, Oct 30, 2009 at 9:35 AM, Tim Ferrell wrote: > >> 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 In this case, sort_by is faster because it creates less DateTime objects. def sort_by_datetime(ary) ary.sort_by {|el| Date.strptime(el, '%A %I:%M %p') } end (see the ri for enumerable#sort_by ). Hth, Siep -- Posted via http://www.ruby-forum.com/.