在此頁面: https://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/105-equality_of_objects有困難解決基本RubyMonk鍛鍊
我試圖糾正這個代碼,以便它通過了測試。 我的嘗試非常糟糕,因爲我只是剛開始學習軟件邏輯的工作原理。
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)
我希望一個Rubyist在那裏可以幫我解決這個練習。我不確定如何解決它。
感謝您的幫助
這裏是從測試的輸出:
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 ✔
你需要改變你的''==方法,這樣,在該情況下'self'不是'other_item'但它們具有相同的名稱('self.item_name == other_item.item_name')和相同的值( sim。for'qty'),它返回'true'。 (實際上,在該類的'=='定義內的對象上調用'=='應該使你進入無限遞歸。) – iamnotmaynard