# What does def <=>( b ) mean?

• Apr 12, 2007, 19:45
What does def <=>( b ) mean?
I'm checking out a class that has the following method definition:

Code:

`def <=>(b)`
I've never seen a
Code:

`<=>`
definition before. what does it mean?

Thanks
--
Jimmy Z
• Apr 13, 2007, 05:02
tconley79
Spaceship
Hi.

This nifty little syntax is called the general comparison operator. Or more affectionately, the "spaceship" operator.

The Pragmatic Programmer's guide defines it as:
Quote:

...the spaceship operator, <=> compares two values, returning -1, 0, or +1 depending on whether the first is less than, equal to, or greater than the second.
The use of this operator is that you can teach ruby how to compare two objects with values that are not intuitively apparent. Suppose you have a Building object, and you want to define one object's superiority over another in terms of their height--without having to expose their instance variables. To set this up, you would first include the module "Comparable" in your class declaration and override it's <=> function:

Code:

```class Building   include Comparable   def <=> (other_building)     self.height <=> other.height      #since "height" is presumably an integer, just call this method again     #because integer objects already know how to compare themselves.   end     #or if you need a more custom operation...   def <=> (other)     if self.height < other.height-50       -1     elsif self.height > other.height+50       1     else       0     end     # this would find two buildings equal if they were within 50 units of     # each other in height. Otherwise it would return the proper result if     #one is more or less than 50 units in height from the other.   end end #then you use could this to compare any Building object using standard comparison operators. if my_building > your_building   puts "My building is taller" end```
• Apr 13, 2007, 18:30
samsm
You can rewrite the alphabet to put u and i together.
• Apr 13, 2007, 19:27
SimplyFu
I try to use
Code:

```def + # .... addition routine end```
but it seems doesn't work. should I use alias
• Apr 14, 2007, 07:00
Luke Redpath
If you are defining your own + method it will need a parameter (the object you are adding).
• Apr 14, 2007, 11:34
Fenrir2
Otherwise use +@.

Code:

```class Something   def +@     "hi"   end end +Something.new  # => "hi"```
This is handy for DSLs.