lundi 27 avril 2015

What is wrong with this Ruby code (I'm assuming it is in the if/else statement)?

The goal of this code is to make it return true if the item_name and qty of the object is the same as that of the object being compared with. With my code, both puts return false.

class Item
    attr_reader :item_name, :qty

    def initialize(item_name, qty)
        @item_name = item_name
        @qty = qty
    end
    def to_s
        "Item (#{@item_name}, #{@qty})"
    end
    def ==(other_item)
      if @item_name.==(@qty)
        true
      else
        false
      end
    end
end

p Item.new("abcd",1)  == Item.new("abcd",1)
p Item.new("abcd",2)  == Item.new("abcd",1)

What should I do to fix it? I have also tried making the if/else statement say the following:

1.

  if @item_name == @qty
    true
  else
    false
  end

2.

  if item_name == qty
    true
  else
    false
  end

3.

  if item_name.==(qty)
    true
  else
    false
  end

Aucun commentaire:

Enregistrer un commentaire