【发布时间】:2016-02-29 10:06:46
【问题描述】:
我定义了一个类User,并像这样覆盖了它的== 运算符:
class User
attr_reader :age
def initialize age
@age = age
end
def ==(other_user)
return true if @age == other_user.age
false
end
end
!= 的默认实现是否使用==?我也不需要覆盖!= 吗?
【问题讨论】:
-
旁注:
==不是运算符,它是一种方法,定义在 [在这种特殊情况下]User类. -
@mudasobwa 事实上两者都是。
def ==定义了一个方法,在使用==操作符时调用。 -
@Stefan 好吧,是的;我的意思是 OP 中提到的是一种方法,而不是运算符。
-
Comparable module 为您提供
<, <=, ==, >=, >和between?方法以换取<=>方法。 (def <=>(other); @age <=> other.age; end)
标签: ruby comparison operator-overloading operators