Ruby 没有将 Fixnum 隐式转换为字符串(TypeError)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20356609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby no implicit conversion of Fixnum into String (TypeError)
提问by stecd
I am trying to answer the following question from Chris Pine's "Learn to Program" book:
我试图从 Chris Pine 的“学习编程”一书中回答以下问题:
Leap years. Write a program that asks for a starting year and an ending year and then puts all the leap years between them (and including them, if they are also leap years). Leap years are years divisible by 4 (like 1984 and 2004). However, years divisible by 100 are not leap years (such as 1800 and 1900) unless they are also divisible by 400 (such as 1600 and 2000, which were in fact leap years). What a mess!
闰年。编写一个程序,询问起始年份和结束年份,然后将所有闰年放在它们之间(如果它们也是闰年,也包括它们)。闰年是能被 4 整除的年份(如 1984 和 2004)。但是,能被 100 整除的年份不是闰年(例如 1800 和 1900),除非它们也能被 400 整除(例如 1600 和 2000,它们实际上是闰年)。真是一团糟!
I get the following error when I run my code:
运行代码时出现以下错误:
leap_year.rb:12:in +': no implicit conversion of Fixnum into String (TypeError)
from leap_year.rb:12:in'
leap_year.rb:12:in +': no implicit conversion of Fixnum into String (TypeError)
from leap_year.rb:12:in'
Here is my code:
这是我的代码:
#leap years
puts 'What is the starting year?'
starting_year = gets.chomp
puts 'What is the ending year?'
ending_year = gets.chomp
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
回答by Nick Veys
回答by Max Woolf
This is because the input from gets.chompis a String. You cannot perform modulo (%) on a String. You need to convert it to an integer first.
这是因为从输入gets.chomp是String。您不能%对String. 您需要先将其转换为整数。
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?
那现在有效吗?

