41

根据文档Array.include?使用==对象的比较。我来自Java,这些事情(通常)完成.equals(),很容易为特定对象覆盖。

如何==在 Ruby 中重写以允许我Array.include?为我的特定对象指定行为?

4

2 回答 2

76

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

class MyClass
  def ==(other_object)
    # return true if self is equal to other_object, false otherwise
  end
end
于 2012-06-25T09:43:06.940 回答
1

如上所述,==是 Ruby 中的一个方法,可以被覆盖。您在方法中编写自定义相等条件。例如:

class Person
  attr_reader :name, :gender, :social_id
  attr_accessor :age

  def initialize(name, age, gender, social_id)
    self.name = name
    self.age = age.to_i
    self.gender = gender
    self.social_id = social_id
  end

  def ==(other)
    social_id == other.social_id
  end
end

您不再需要覆盖其他方法。

于 2020-07-09T14:31:39.570 回答