The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Spaceship

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