在Ruby中覆盖==运算符

问题描述:

根据 docs 数组.包括?对对象使用 == 比较.我来自Java,通常使用 .equals()完成这些操作,对于特定对象而言,该操作很容易覆盖.

According to the docs, Array.include? uses the == comparison on objects. I come from Java where such things are (usually) done with .equals() which is easy to override for a particular object.

如何在Ruby中覆盖 == 以允许我为特定对象指定 Array.include?​​ strong>的行为?

How can I override == in Ruby to allow me to specify the behaviour of Array.include? for my particular object?

非常感谢.

在Ruby中,==只是一种方法(顶部带有一些语法糖,允许您编写foo == bar而不是foo.==(bar)),并且您覆盖了==就像您使用其他任何方法一样:

In Ruby == is just a method (with some syntax sugar on top allowing you to write foo == bar instead of foo.==(bar)) and you override == just like you would any other method:

class MyClass
  def ==(other_object)
    # return true if self is equal to other_object, false otherwise
  end
end