<=>(p1)
public
Compares the two dates and returns -1, zero, 1 or nil. The other should be a date object or a numeric value as an astronomical Julian day number.
Date.new(2001,2,3) <=> Date.new(2001,2,4) #=> -1 Date.new(2001,2,3) <=> Date.new(2001,2,3) #=> 0 Date.new(2001,2,3) <=> Date.new(2001,2,2) #=> 1 Date.new(2001,2,3) <=> Object.new #=> nil Date.new(2001,2,3) <=> Rational(4903887,2) #=> 0
See also Comparable.
Register or
log in
to add new notes.
lazylester -
March 12, 2009
1 thank
Comparing Date with Numeric in mixed sort
While:
Date#<=>(other)
can accept a Numeric object as other, the reverse is not true:
Numeric#<=>(other)
cannot accept a Date object as other.
So if you are sorting a list containing a mix of dates and numbers, you can get different results depending on the starting order!
a = Date.parse("2008-01-01") b = Date.parse("2009-10-22") c = Date.parse("2005-01-04") d = 0 [a,b,c,d].sort #=> [0, Tue, 04 Jan 2005, Tue, 01 Jan 2008, Thu, 22 Oct 2009] [b,c,d,a].sort #=> ArgumentError: comparison of Fixnum with Date failed