简体   繁体   English

Ruby gets.chomp和类继承

[英]Ruby gets.chomp and class inheritance

I've been trying to write a code for checking whether the number is a leap year with class inheritance. 我一直在尝试编写代码来检查数字是否是具有类继承的a年。 But I got an error message on the second line which starts with year : 但是我在以year开头的第二行上收到一条错误消息:

Line 7: private method `chomp' called for nil:NilClass (NoMethodError)

I want to make users type the years and then return the responses respectively ---"It's a leap year!" 我想让用户键入年份,然后分别返回响应---“这是a年!” or "Oops! It's not a leap year". 或“糟糕!这不是a年”。 But it seems to me that gets.chomp and class collide with each other. 但是在我看来, gets.chompclass相互冲突。 How can I solve this problem? 我怎么解决这个问题?

Below is my code(I amended the former one yet it still doesn't work): 以下是我的代码(我修改了前一个代码,但仍然无法正常工作):

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

Thank you. 谢谢。 :) :)

Change 更改

year = gets.chomp

to

year = gets.to_s.chomp

Calling to_s will convert your nil to an empty string. 调用to_s会将您的nil转换为空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM