From: Robert Klemme Date: 2011-06-07T23:25:38+09:00 Subject: Re: Ruby 1.9 Time parse question On Tue, Jun 7, 2011 at 3:35 PM, Paul wrote: > Hi there! > > I have a ruby program that works as expected with 1.8.6 and 1.8.7. I > just discovered some failures with some functions when i ran it in > 1.9.2. > > The line that is breaking is: >> data_array.sort! { |a,b| Time.parse( b[1]+' '+b[2] ) <=> Time.parse( a[1]+' '+a[2] ) } > > the data is an AoA and looks like: > data_array = [ ['1', '04/14/2011', '10:00 am', 'foo'], >  ['2', '04/18/2011', '03:30 pm', 'bar'], >  ['3', '04/18/2011', '11:15 am', 'baz']] > > => so I expect the elements to resort as: 1, 3, 2. > > I want to use code that will work in both 1.8 and 1.9 using the > standard Ruby libraries for maximum portability. > > In 1.8, the Time.parse method works with the 'mm/dd/yyyy' format, > while in 1.9 it is looking for 'dd/mm/yyyy'. > > Is there a nice clean way to sort this array by date and time that > will work in both 1.8 and 1.9? You should give the format explicitly: 16:22:52 ~$ allruby -r date -e 'puts Date.strptime("04/14/2011", "%m/%d/%Y")' CYGWIN_NT-5.1 padrklemme2 1.7.9(0.237/5/3) 2011-03-29 10:10 i686 Cygwin ======================================== ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin] 2011-04-14 ======================================== ruby 1.9.2p180 (2011-02-18 revision 30909) [i386-cygwin] 2011-04-14 ======================================== jruby 1.6.1 (ruby-1.8.7-p330) (2011-04-12 85838f6) (Java HotSpot(TM) Client VM 1.6.0_25) [Windows XP-x86-java] 2011-04-14 ======================================== jruby 1.6.1 (ruby-1.9.2-p136) (2011-04-12 85838f6) (Java HotSpot(TM) Client VM 1.6.0_25) [Windows XP-x86-java] 2011-04-14 ======================================== You can as well do the parsing yourself: 16:25:00 ~$ allruby -r date -e 'm,d,y="04/14/2011".scan(/\d+/).map {|x|x.to_i};puts Date.new(y,m,d)' CYGWIN_NT-5.1 padrklemme2 1.7.9(0.237/5/3) 2011-03-29 10:10 i686 Cygwin ======================================== ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin] 2011-04-14 ======================================== ruby 1.9.2p180 (2011-02-18 revision 30909) [i386-cygwin] 2011-04-14 ======================================== jruby 1.6.1 (ruby-1.8.7-p330) (2011-04-12 85838f6) (Java HotSpot(TM) Client VM 1.6.0_25) [Windows XP-x86-java] 2011-04-14 ======================================== jruby 1.6.1 (ruby-1.9.2-p136) (2011-04-12 85838f6) (Java HotSpot(TM) Client VM 1.6.0_25) [Windows XP-x86-java] 2011-04-14 ======================================== Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/