Robert Klemme
7/31/2006 3:44:00 PM
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