我遇到了'无法将Fixnum转换为String(TypeError)'错误,虽然看起来很简单,但我不确定如何绕过它。我认为我的逻辑是合理的 - 将输入的字符串变量转换为整数然后执行基本操作 - 但显然我缺少一些关键信息。
puts 'What is your favourite number?'
favenum = gets.chomp
better = favenum.to_i + 1
puts 'Yeah '+favenum+' is nice enough but '+better+' is bigger and better by far! Think on.'
我们已经尝试过寻找答案,但目前还有超出我的基本红宝石技能的相同错误的例子。
答案 0 :(得分:48)
Ruby(与其他语言不同)当它们是String#+
方法中的操作数时,不会将对象强制转换为字符串。要么手动转换为字符串:
puts 'Yeah ' + favenum.to_s + ' is nice enough but ' + better.to_s + ' is bigger and better by far!'
或使用字符串插值(注意双引号):
puts "Yeah #{favenum} is nice enough but #{better} is bigger and better by far!"
答案 1 :(得分:5)
尝试使用字符串插值,如下所示:
puts "Yeah #{favenum} is nice enough but #{better} is bigger and better by far! Think on."
答案 2 :(得分:2)
根据您正在关注的教程
puts 'Please enter your favourite number: '
number = gets.chomp
imp = number.to_i + 1
puts 'I\'d say '.to_s + imp.to_s + ' is a much better number.'
在初学者级别生成“正确”的结果。