From: Robert Klemme Date: 2006-08-01T00:45:07+09:00 Subject: Re: Weird elusive bug using Comparable Pedro C�rte-Real wrote: > 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 # shorter SimpleDate = Struct.new :year, :month, :day do include Comparable def <=> (other) self.class.members.each do |field| result = send(field) <=> other.send(field) return result unless result == 0 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. No, it's differently implemented. Kind regards robert