[英]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.