Ruby没有将Fixnum转换为String(TypeError)怎么办?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (11)

有一个题目:敲起始年和中止年,并计算其中闰年数量

当我运行我的代码时,出现以下错误:

leap_year.rb:12:in+': no implicit conversion of Fixnum into String (TypeError) from leap_year.rb:12:in'

这是我的代码:

#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
提问于
用户回答回答于

添加.to_igets.chomp

你正在尝试对文本进行数学运算。当从控制台输入时,所有内容都以文本形式出现,即使它是数字文本。

用户回答回答于

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

扫码关注云+社区