Home > database >  Does overriding == for a object change the behavior of include? method of an array?
Does overriding == for a object change the behavior of include? method of an array?

Time:01-26

Example:

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

My question is does the array include? method compare two objects bases on the defination of == method?

Bascially, will the above code determine whether my new_custom_object is included in the array of CustomObject by evaluating the overridden == method for each insance of CustomObject in the array with new_custom_object?

CodePudding user response:

My question is does the array include? method compare two objects bases on the defination of == method?

Yes. As said in: https://ruby-doc.org/3.2.0/Array.html#method-i-include-3F

include?(obj) → true or false click to toggle source

Returns true if for some index i in self, obj == self[i]; otherwise false:


Seems to be working, (though I'm not sure if this is the most optimal way of doing things as we don't know the context of your code):

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
  • Related