Ruby no implicit conversion of Fixnum into String (TypeError)

前端 未结 2 2043
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-12 12:52

I am trying to answer the following question from Chris Pine\'s \"Learn to Program\" book:

Leap years. Write a program that asks for a starting year and a

2条回答
  •  一个人的身影
    2021-02-12 13:03

    This is because the input from gets.chomp is a String. You cannot perform modulo (%) on a String. You need to convert it to an integer first.

    Try this...

    puts 'What is the starting year?'
    starting_year = gets.chomp.to_i
    puts 'What is the ending year?'
    ending_year = gets.chomp.to_i
    
    while starting_year <= ending_year
      if starting_year%4 == 0 && (starting_year%100 != 0 && starting_year%400 == 0)
        puts starting_year 
      end 
      starting_year+=1
    end
    

    Does that work now?

提交回复
热议问题