2012-04-11 111 views
0

我想在ruby中編寫一個模塊,並且每當我使用比較運算符時,我都會收到上述錯誤。沒有一個操作員工作。未定義的方法`> ='爲零:NilClass(NoMethodError)

if self.health >= opponent.health 
     [:attack, opponent] 
    else 
     [:rest] 
    end 

請讓我知道我是否犯了某種錯誤。

謝謝!

+1

你確定'self.health'不是'nil'嗎?因爲這就是錯誤信息所宣稱的...(可能是你的代碼中某個地方出現錯字?) – user1252434 2012-04-11 14:55:10

回答

1

>=只能用於Comparable對象。您的錯誤消息表明self.healthnil。您需要爲self.healthopponent.health設置一個Comparable對象,並在它們之間進一步進行比較。

+0

'Comparable'實現'> =' - 而不是'Enumerable'。 http://ruby-doc.org/core-1.8.6/Comparable.html – thomthom 2012-04-11 14:49:54

+0

@thomthom感謝您糾正我的錯誤。我修好了它。 – sawa 2012-04-11 14:51:27

+0

不完全。 '> ='方法可以添加到任何類中,並在比較的情況下使用。此外,錯誤文本包含不包含請求方法的對象的類,在這種情況下爲'NilClass',可以合理地預期它是無法比擬的。 ;) – user1252434 2012-04-11 15:04:47

0

正如@sawa說,你是比較引發異常的原因是,self.healthnil,該方法爲其>=沒有定義(儘管@ user1252434如前所述,Comparable解釋是不太正確的。方法>=可以在任何等級中定義,具有或不具有模塊Comparable)。根據您的比較結果,這種類型的比較可能很容易使用默認值。對於String對象,你可以調用to_s使用""(空字符串)爲您比較的默認:

self.health.to_s >= opponent.health.to_s 
#Compares "" >= "" if the attributes are nil 

對於Fixnum對象的對象(整數),你可以使用to_i使用0作爲默認:

self.health.to_i >= opponent.health.to_i 
#Compares 0 >= 0 if the attributes are nil 

而對於浮動對象,你可以使用to_f使用0.0作爲默認:

self.health.to_f >= opponent.health.to_f 
#Compares 0.0 >= 0.0 if the attributes are nil 
相關問題