2014-05-13 53 views
1

在此頁面: 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 ✔ 
+0

你需要改變你的''==方法,這樣,在該情況下'self'不是'other_item'但它們具有相同的名稱('self.item_name == other_item.item_name')和相同的值( sim。for'qty'),它返回'true'。 (實際上,在該類的'=='定義內的對象上調用'=='應該使你進入無限遞歸。) – iamnotmaynard

回答

4

當你重寫==方法,你應該給意義的比較。默認行爲==檢查,其他產品相同於比較的項目(它們具有相同的object_id)。試試這個:

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

可以指出你在正確的方向,而不是告訴答案。

您正在比較對象的參考值是否相等,而您是要求僅比較那些相等的屬性。也就是說,比較兩個對象參數的方式,如果它們相等,則必須返回true;否則false

1

當你過去的問題向下滾動,你會看到下面的例子提供了一個明確的解決方案。