ruby 重写对象的==是否会改变数组的include?方法的行为?

ebdffaop  于 2023-01-25  发布在  Ruby
关注(0)|答案(1)|浏览(129)

示例:

class CustomObject
  .....
  def ==(other)
    self.x == other.x && self.y =! other.y
  end
  .....
end

array_of_custom_objects = CustomObject.load_for(company_id: company_id)
new_custom_object = CustomObject.new(....)

array_of_custom_objects.include? new_custom_object

我的问题是数组include?方法是否基于==方法的定义来比较两个对象?
基本上,上面的代码是否通过为数组中CustomObject的每个示例计算被重写的**==方法来确定我的new_custom_object是否包含在CustomObject**数组中?

vq8itlhq

vq8itlhq1#

我的问题是数组include?方法是否基于==方法的定义来比较两个对象?
是的。如中所述:https://ruby-doc.org/3.2.0/Array.html#method-i-include-3F
包含?(obj)→点击切换源的真或假
返回真,如果对于self中的某个索引i,obj == self[i];否则为假:
似乎是工作,(虽然我不确定这是否是最佳的方式做的事情,因为我们不知道你的代码的上下文):

class CustomObject
  attr_reader :x, :y, :z

  def initialize(x, y, z)
    @x = x
    @y = y
    @z = z
  end

  def ==(other)
    self.x == other.x && self.y != other.y
  end
end

custom_objects = []
new_custom_object_1 = CustomObject.new(1, 2, 3)
custom_objects << new_custom_object_1

new_custom_object_2 = CustomObject.new(2, 3, 4)
custom_objects << new_custom_object_2

search_object = CustomObject.new(2, 7, 4) # 2 == 2 && 3 != 7

puts custom_objects.include?(search_object)
# => true

search_object = CustomObject.new(2, 3, 4) # 2 == 2 && 3 != 3

puts custom_objects.include?(search_object)
# => false

相关问题