Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having difficulty solving basic RubyMonk exercise

Tags:

ruby

On this page: https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/105-equality_of_objects

I am trying to correct this code, so that it passes its tests. My attempt is quite bad as I am only just beginning to learn how software logic works.

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)
    end
end

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

This is my solution, but it is not correct:

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 self == other_item
         return true
       else
         return false
       end
    end
end

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

I was hoping a Rubyist out there could help me solve this exercise. I am unsure of how to solve it.

Thanks for your help

here is the output from the test:

STDOUT:
nil
nil
Items with same item name and quantity should be equal
RSpec::Expectations::ExpectationNotMetError
expected Item (abcd, 1) got Item (abcd, 1) (compared using ==) Diff:
Items with same item name but different quantity should not be equal ✔
Items with same same quantity but different item name should not be equal ✔
like image 200
Patrick Meaney Avatar asked Feb 28 '26 05:02

Patrick Meaney


1 Answers

When you override the == method, you should give meaning to your comparison. The default == behavior checks that the other item is identical to the compared item (they have the same object_id). Try this:

def ==(other_item)
   other_item.is_a?(Item) && 
     self.item_name == other_item.item_name && 
     self.qty == other_item.qty
end
like image 120
Uri Agassi Avatar answered Mar 02 '26 18:03

Uri Agassi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!