解决基本RubyMonk练习有困难

wfsdck30  于 2023-01-30  发布在  Ruby
关注(0)|答案(4)|浏览(149)

本页内容:https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/105-equality_of_objects
我正试图纠正这段代码,使它通过测试。我的尝试相当糟糕,因为我才刚刚开始学习软件逻辑是如何工作的。

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)

这是我的解决方案,但它是不正确的:

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)

我希望有一个RubyMaven能帮我解决这个问题。我不知道如何解决它。
谢谢你的帮忙
下面是测试的输出:

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 ✔
8cdiaqws

8cdiaqws1#

覆盖==方法时,应该为比较给予意义。默认的==行为检查另一项是否与比较项“相同”(它们具有相同的object_id)。请尝试以下操作:

def ==(other_item)
   other_item.is_a?(Item) && 
     self.item_name == other_item.item_name && 
     self.qty == other_item.qty
end
ddarikpa

ddarikpa2#

能给你指出正确的方向而不是告诉你答案。
你正在比较对象的引用是否相等,然而,你被要求只比较那些属性是否相等,也就是说,比较两个对象的参数,如果它们相等,它必须返回true;否则false

uurv41yg

uurv41yg3#

当您向下滚动经过问题时,您将看到下一个示例提供了清晰的解决方案。

fcipmucu

fcipmucu4#

类项目属性读取器:项目名称,:数量

def initialize(item_name, qty)
    @item_name = item_name
    @qty = qty
end
def to_s
    "Item (#{@item_name}, #{@qty})"
end
def ==(other_item)
  self.item_name == other_item.item_name && 
  self.qty == other_item.qty
end

结束
pItem.new(“abcd”,1)==新项目(“abcd”,1)p新项目(“abcd”,2)==新项目(“abcd”,1)

相关问题