[英]Ruby gets.chomp and class inheritance
我一直在嘗試編寫代碼來檢查數字是否是具有類繼承的a年。 但是我在以year
開頭的第二行上收到一條錯誤消息:
Line 7: private method `chomp' called for nil:NilClass (NoMethodError)
我想讓用戶鍵入年份,然后分別返回響應---“這是a年!” 或“糟糕!這不是a年”。 但是在我看來, gets.chomp
和class
相互沖突。 我怎么解決這個問題?
以下是我的代碼(我修改了前一個代碼,但仍然無法正常工作):
class Year
def initialize(year)
@@year = year
end
puts "Type the year to see whether it is a leap year!"
year = gets.chomp
end
class DivideIt
def initialize(year)
@year = year
end
if @year % 4 == 0 || @year % 100 != 0 || @year % 400 == 0
return true
else
return false
end
end
year < DivideIt
謝謝。 :)
更改
year = gets.chomp
至
year = gets.to_s.chomp
調用to_s
會將您的nil
轉換為空字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.