根据docs,Array.include?
在对象上使用==
比较.我来自Java,在Java中,这样的事情(通常)是用.equals()
完成的,.equals()
很容易为特定对象重写.
如何在Ruby中重写==
,以便为特定对象指定Array.include?
的行为?
根据docs,Array.include?
在对象上使用==
比较.我来自Java,在Java中,这样的事情(通常)是用.equals()
完成的,.equals()
很容易为特定对象重写.
如何在Ruby中重写==
,以便为特定对象指定Array.include?
的行为?
在Ruby中,==
只是一个方法(上面有一些语法糖,允许您编写foo == bar
而不是foo.==(bar)
),您可以像重写任何其他方法一样重写==
:
class MyClass
def ==(other_object)
# return true if self is equal to other_object, false otherwise
end
end