"Tim Hunter" <cyclists / nc.rr.com> writes:

> 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. 

I have to say I disagree with this fairly strongly. 

> 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.

There's a boat load of difference between coercion and "being the same
class". For example, following your code example would mean that

   1 <=> 1.2

would raise a type error.

I honestly believe that the correct thing to do is not to check the
class (or the methods implemented) of your argument.  Instead, assume
the person using your class has half a brain. They may deliberately
pass a String in to a method designed to work with Files, knowing that
the << operator works fine with both. They may well pass a Float into
class Fixnum's <=> method, knowing that the right thing will be done.

You might choose to implement coercion in your own class if you feel
it worthwhile. You can do something as simple as calling a 'to_xxx'
method, or you can use something similar to the Numeric coerce
scheme. Depending on the circumstances, this might be a friendly move.

Overzealously checking the class of parameters defeats much of the
point of Ruby.


Regards


Dave