Forum: JRuby Weird behavior in Array#sort of 2 Time objects

420291e1b7d022cf4fe73023ab345672?d=identicon&s=25 Brad P. (brad_p)
on 2012-05-12 19:31
I'm seeing some very strange behavior while trying to sort an array with
2 elements.  Here is the code:

      work_periods = day_array[wday] || []
      puts "work_periods=#{work_periods.inspect}"
      puts "work_periods.length=#{work_periods.length}"
      begin
        work_periods = work_periods.sort { |a,b| puts
"a=#{a.start_time.class.inspect} b=#{b.start_time.class.inspect}"; stat
= (a.start_time < b.start_time); puts "stat=#{stat}"; stat }
      rescue Exception => e
        puts "e=#{e.message}\n\t#{e.backtrace.join("\n\t")}"
        raise
      end
      puts "got here"

And here is the output:

work_periods=[#<WorkPeriod id: 6, weekly_schedule_id: 2, site_id: 1,
day: 1, start_time: "2000-01-01 08:00:00", end_time: "2000-01-01
12:00:00">, #<WorkPeriod id: 476, weekly_schedule_id: 2, site_id: 2,
day: 1, start_time: "2000-01-01 14:00:00", end_time: "2000-01-01
17:00:00">]
work_periods.length=2
a=Time b=Time
stat=false
e=undefined method `>' for false:FalseClass
  org/jruby/RubyArray.java:3252:in `sort!'
  org/jruby/RubyArray.java:3226:in `sort'
  /Users/rugger/Documents/acme/app/models/weekly_schedule.rb:24:in
`each_out_of_office_time'
  org/jruby/RubyRange.java:445:in `each'

Anyone have any idea whats going on?  Either I'm missing something
completely obvious or I'm running into a JRuby bug.  I'm using 1.6.7 in
1.9 mode.
0f36963d10e423a204db6aa255fd308f?d=identicon&s=25 Rohit Namjoshi (Guest)
on 2012-05-13 02:48
(Received via mailing list)
The block passed to sort needs to return -1, 0, +1.
http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-sort

work_periods.sort! {|a, b| a.start_time <=> b.start_time}

Timestamps should be instances of Time or DateTime rather than String
420291e1b7d022cf4fe73023ab345672?d=identicon&s=25 Brad P. (brad_p)
on 2012-05-13 14:06
Yes, I feel like an idiot.  Thanks for the help!
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.