Hi --

On Sat, 23 Nov 2002, Tim Hunter wrote:

> At Gavin's request here is a summary of my question and the answers I
> received.
>
> Q: I've defined a class whose objects may be ordered. What should
> my <=> method do when the "other" argument is not in the same
> class?
>
> A. Raise a TypeError exception. The <=> method in most of Ruby's
> built-in classes will raise a TypeError exception if "other"
> can't be coerced into the same class.
>
> If you want your class to include the other comparision operators
> such as ==, <=, =>, etc., consider mixing in the Comparable module.
> This module implements these other comparison operators by calling
> your <=> method. For example,
>
> class TestClass
>    include Comparable
>
>    def <=>(other)
>       unless other.kind_of? self.class
> 	      raise TypeError, "#{other.class} can't be coerced into #{self.class}"

I'm not sure this error message makes sense.  All you've discovered is
that the other object is not of the same class as the current object;
there's been no further test or coercion attempted.  In fact, some
objects are happy to masquerade as other objects:

  class S
    def to_str
      "ABC"
    end
  end

  s = S.new
  p s.kind_of?(String)     # false
  p Regexp.new(s)          # /ABC/
  p "Some string" <=> s    # 1

or simply to respond to the necessary messages without being of the
same class.  This may or may not be what you want in a given case, but
I think the kind_of? test probably isn't an all-purpose way to
conceptualize the <=> implementation.


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav