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

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

2. ## 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:
...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```

3. You can rewrite the alphabet to put u and i together.

4. I try to use
Code:
```def +
end```
but it seems doesn't work. should I use alias

5. If you are defining your own + method it will need a parameter (the object you are adding).

6. Otherwise use +@.

Code:
```class Something
def +@
"hi"
end
end

+Something.new  # => "hi"```
This is handy for DSLs.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•