矩形可按面积比较
Comparable
是 Ruby 中最受欢迎的模块之一。其目的是提供方便的比较方法。
要使用它,你必须 include Comparable
并定义太空船运算符(<=>
):
class Rectangle
include Comparable
def initialize(a, b)
@a = a
@b = b
end
def area
@a * @b
end
def <=>(other)
area <=> other.area
end
end
r1 = Rectangle.new(1, 1)
r2 = Rectangle.new(2, 2)
r3 = Rectangle.new(3, 3)
r2 >= r1 # => true
r2.between? r1, r3 # => true
r3.between? r1, r2 # => false