user2231215
user2231215

Reputation: 29

User defined Objects equality always returns false

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

Upvotes: 2

Views: 136

Answers (3)

Max Makarochkin
Max Makarochkin

Reputation: 79

People post answers too fast. Anyway, this code works:

class Product
  attr_reader :name, :qty

  def initialize(name, qty)
    @name = name
    @qty = qty
  end

  def ==(other_product)
    name == other_product.name && qty == other_product.qty
  end
end

Product.new("Amazon", 3) == Product.new("Amazon", 3)

Upvotes: 0

Pol0nium
Pol0nium

Reputation: 1386

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.

Upvotes: 4

WyssMan
WyssMan

Reputation: 66

First of all, you will get a lot more responses if you format your code correctly and are careful to phrase your questions so that you are understood.

Second of all, you could find the was Ruby handles equality from the Ruby documentation. Ruby has many different types of equals. They are implemented (as most/every thing in ruby) as methods on an object.

Object has default implementations. http://ruby-doc.org/core-2.0.0/Object.html

== will by default check that the instances are identical (addresses and all).

You can override it as a method in your class to give a better meaning.

Upvotes: 0

Related Questions