Ruby no implicit conversion of Fixnum into String (TypeError)

纵饮孤独 提交于 2019-12-03 10:46:56

Add a .to_i to your gets.chomp calls. You're trying to do math operations on text. When inputted from the console, everything starts out as text, even if it's numeric looking text.

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?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!