I'm checking out a class that has the following method definition:
I've never seen aCode:def <=>(b)definition before. what does it mean?Code:<=>
Thanks
--
Jimmy Z
| SitePoint Sponsor |
I'm checking out a class that has the following method definition:
I've never seen aCode:def <=>(b)definition before. what does it mean?Code:<=>
Thanks
--
Jimmy Z
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 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:...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.
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





You can rewrite the alphabet to put u and i together.
Using your unpaid time to add free content to SitePoint Pty Ltd's portfolio?




I try to use
but it seems doesn't work. should I use aliasCode:def + # .... addition routine end
If you are defining your own + method it will need a parameter (the object you are adding).




Otherwise use +@.
This is handy for DSLs.Code:class Something def +@ "hi" end end +Something.new # => "hi"
Bookmarks