Class Product
def initialize(name, qty)
@name = name
@qty = qty
end
def to_s
"#{@name}, #{@qty}"
end
end
irb> Product.new("Amazon", 3) == Product.new ("Amazon", 3)
irb> false
Ruby always returns false for these type of user defined objects which is wrong, how to make them true if they are equal and false if they are not equal
You should implement the comparison operator.
Example :
Class Product
attr_reader :name, :qty
def initialize(name, qty)
@name = name
@qty = qty
end
def to_s
"#{@name}, #{@qty}"
end
def ==(another_product)
self.name == another_produc.name and self.qty == another_product.qty
# or self.to_s == another_product.to_s
end
end
More info : ruby equality and object comparison
Explanation :
In your example, ruby doesn't know how to compare your object. So ruby compares two adresses (where the objects are stored) and says that the two addresses are different.
If you specify in your class the ==
operator, ruby now knows how to compare your objects.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments