运算符 `!=` 是否使用 `==`?

Does the operator `!=` use `==`?

我定义了一个 class 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

!= 的默认实现是否使用 ==?我也不需要覆盖 != 吗?

除非 class 层次结构中的任何 class 被覆盖 !=,否则将调用 BasicObject#!= 上的默认实现。

如果您在我链接的页面上点击“点击切换源”,您会看到默认实现

 VALUE
rb_obj_not_equal(VALUE obj1, VALUE obj2)
{
    VALUE result = rb_funcall(obj1, id_eq, 1, obj2);
    return RTEST(result) ? Qfalse : Qtrue;
}

简单地调用==并对返回值求反。

也就是说,虽然您可以确定,您的 class 的祖先没有覆盖 BasicObject#!= 的默认行为,但仅覆盖 == 是安全的.

是也不是。

==!= 都是方法,您可以随时单独覆盖它们。

class X
  def ==(other)
    true
  end

  def !=(other)
    true
  end
end

a = X.new
b = X.new

a == b  #=> true
a != b  #=> true

默认情况下,!= 使用 ==