[FAQ] Defining <=>

Seems like I should take another stab at this one. Thanks to everyone
for their input.

I deliberately chose to only cursorily address the general issue of
"type-checking." That topic more than merits its own entry. If, by
omitting that topic, I’ve rendered this particular entry pointless,
so be it. It could well be argued that the answer to this question
should simply be “A: Nothing.”

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?

it during comparison, Ruby will raise an exception for you. You can, of
course, trap the exception and put out your own error message. OTOH, if
"other" does respond appropriately, your <=> will never know the
difference.

In some cases you can try to coerce “other” to an appropriate type
using a to_xxx method. For example, if you need a String, try to coerce
"other" to a String by sending it to_s.

Lastly, objects in some application- or domain-specific classes may not be
reasonably compared to any other objects. If this applies to your class
you may wish to use kind_of? to ensure that “other’s” type is correct.
If not, raise TypeError. The benefit of doing this is that you can
catch errors early and potentially produce more meaningful error messages.
However, keep in mind that checking the class of method arguments is
frequently considered bad Ruby style.

If you want your class to include the other comparision operators
such as ==, <=, =>, etc., mix in in the Comparable module.
This module implements these other comparison operators by calling
your <=> method.

···

A: Probably nothing. If “other” doesn’t respond to the methods you send