P
Pedro Côrte-Real
I have this class:
class SimpleDate
include Comparable
VALS = [:year, :month, :day]
attr_accessor *VALS
def initialize(year, month, day)
@year = year
@month = month
@day = day
end
#ideas on making this much shorter are welcome
def <=>(other)
VALS.each do |key|
v1 = self.send(key)
v2 = other.send(key)
result = (v1 <=> v2)
if result != 0
return result
end
end
0
end
end
that represents a date that might have any of the three parts not
existant. For some reason date1 == date2 returns nil when done like
this:
class SimpleDateTest < Test::Unit::TestCase
def test_comparison_with_nils
date1 = SimpleDate.new(1,nil,nil)
date2 = SimpleDate.new(1,nil,nil)
assert_not_equal date1.object_id, date2.object_id
assert date1 == date2
end
end
The code shouldn't even work because nil doesn't implement <=>. What
the hell is comparable doing behind my back?
I thought date1 == date2 was the same as (date1 <=> date2> == 0 but
apparently not.
Pedro.
class SimpleDate
include Comparable
VALS = [:year, :month, :day]
attr_accessor *VALS
def initialize(year, month, day)
@year = year
@month = month
@day = day
end
#ideas on making this much shorter are welcome
def <=>(other)
VALS.each do |key|
v1 = self.send(key)
v2 = other.send(key)
result = (v1 <=> v2)
if result != 0
return result
end
end
0
end
end
that represents a date that might have any of the three parts not
existant. For some reason date1 == date2 returns nil when done like
this:
class SimpleDateTest < Test::Unit::TestCase
def test_comparison_with_nils
date1 = SimpleDate.new(1,nil,nil)
date2 = SimpleDate.new(1,nil,nil)
assert_not_equal date1.object_id, date2.object_id
assert date1 == date2
end
end
The code shouldn't even work because nil doesn't implement <=>. What
the hell is comparable doing behind my back?
I thought date1 == date2 was the same as (date1 <=> date2> == 0 but
apparently not.
Pedro.