简体   繁体   中英

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. But I got an error message on the second line which starts with 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!" or "Oops! It's not a leap year". But it seems to me that gets.chomp and class collide with each other. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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