我正在尝试计算由种族决定的年龄,种族和估计的生命长度。但我在这里遇到了一个问题,特别是最后一行代码。有人可以帮忙吗?
puts "What year were you born? "
age = gets
puts age
var1 = age
puts "sorry, i am a slow computer... What year is it?"
year = gets
var2 = "2013"
puts "ok it is" + year + "so you must be"
puts var2 - var1.to_i
答案 0 :(得分:1)
你是在正确的轨道,但问题是你没有将var2转换为整数,ruby解释器将其视为一个字符串因此错误。这是正确的代码。
puts "What year were you born? "
age = gets
puts age
var1 = age
puts "sorry, i am a slow computer... What year is it?"
year = gets
var2 = "2013"
puts "ok it is" + year + "so you must be"
puts var2.to_i - var1.to_i
答案 1 :(得分:1)
您正尝试从字符串中减去一个整数。这会引发错误。
我认为你正在寻找类似的东西;
puts "What year were you born?"
born = gets.chomp
puts "sorry, i am a slow computer... What year is it?"
date = gets.chomp
age = date.to_i - born.to_i
puts "ok it is #{date} so you must be #{age}"
答案 2 :(得分:0)
var2是一个字符串,因为你在一年中都有引号。 只需在var2上使用.to_i,你应该没问题。