For*_*rge 1 ruby comparison operator-overloading operators
我定义了一个类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
Run Code Online (Sandbox Code Playgroud)
是否默认!=使用==?我不需要覆盖!=吗?
除非!=重写类层次结构中的任何类,否则BasicObject#!=将调用默认实现.
如果您在我链接的页面上单击"单击以切换源",您将看到默认实现
VALUE
rb_obj_not_equal(VALUE obj1, VALUE obj2)
{
VALUE result = rb_funcall(obj1, id_eq, 1, obj2);
return RTEST(result) ? Qfalse : Qtrue;
}
Run Code Online (Sandbox Code Playgroud)
只需调用==并否定返回的值.
也就是说,虽然您确定,您的班级的祖先没有超越默认行为BasicObject#!=,但==仅覆盖是安全的.