define how to compare
use Comparable module & define <=> method
the return value of method <=> , 1, 0 , & -1 decides greater than, equal than, & less than
ex:
class Rabbit
include Comparable
attr_accessor :name
def <=> (other_rabbit)
if self.name <>
-1
elsif self.name > other_rabbit.name
1
else
0
end
end
end
if the thing to compare know how to compare, there is a shorter definition
ex:
def <=> (other_rabbit)
self.name<=> other_rabbit.name
end
沒有留言:
張貼留言