我已经使用强制来处理算术运算符:
class MyCustomClass
def coerce( other )
[MyCustomClass.new(other), self]
end
end
这意味着我可以做到:
42 + MyCustomClass.new
我想知道是否存在允许我进行比较的类似机制(无需猴子修补Fixnum
):
42 > MyCustomClass.new
我已经使用强制来处理算术运算符:
class MyCustomClass
def coerce( other )
[MyCustomClass.new(other), self]
end
end
这意味着我可以做到:
42 + MyCustomClass.new
我想知道是否存在允许我进行比较的类似机制(无需猴子修补Fixnum
):
42 > MyCustomClass.new
您只需要包含Comparable
并定义<=>
运算符:
class MyCustomClass
include Comparable
# ...
def <=>(other)
# e.g. compare self to fixnum and return -1, 0, 1
end
end