Forge
Forge

Reputation: 6844

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

I defined a class User, and overrode its == operator like this:

class User
  attr_reader :age

  def initialize age
    @age = age
  end

  def ==(other_user)
    return true if @age == other_user.age
    false
  end
end

Does the default implementation of != use ==? Do I not need to override != as well?

Upvotes: 1

Views: 62

Answers (2)

Aetherus
Aetherus

Reputation: 8898

Yes and no.

Both == and != are methods, thus you can always override them individualy.

class X
  def ==(other)
    true
  end

  def !=(other)
    true
  end
end

a = X.new
b = X.new

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

By default, != uses ==.

Upvotes: -1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Unless any class in the class hierarchy has != overridden, the default implementation on BasicObject#!= will be called.

If you’ll click on “click to toggle source” on the page I linked, you’ll see that the default implementation

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

simply calls == and negates the returned value.

That said, while you are certain, that no ancestor of your class overrode the default behaviour of BasicObject#!=, it is safe to override == only.

Upvotes: 7

Related Questions