ruby '+' 无法将 Fixnum 转换为 String (TypeError)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14895594/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:45:21  来源:igfitidea点击:

'+' can't convert Fixnum into String (TypeError)

ruby

提问by Dan Solo

I've hit upon a 'can't convert Fixnum into String (TypeError)' error and whilst it seems simple enough I'm unsure about how to get around it. I thought my logic was sound - convert the entered string variable to an integer and then carry out the basic operation - but apparently I'm missing some key bit of information.

我遇到了“无法将 Fixnum 转换为字符串(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.'    

Have tried searching for an answer but examples of the same error out there are way beyond my rudimentary ruby skills at present.

已尝试寻找答案,但目前出现相同错误的示例远远超出了我的基本 ruby​​ 技能。

回答by Sergio Tulentsev

Ruby (unlike some other languages) does not cast objects to strings when they are operands in String#+method. Either cast to string manually:

当对象是String#+方法中的操作数时,Ruby(与其他一些语言不同)不会将对象转换为字符串。手动转换为字符串:

puts 'Yeah ' + favenum.to_s + ' is nice enough but ' + better.to_s + ' is bigger and better by far!'

or use string interpolation (note the double quotes):

或使用字符串插值(注意双引号):

puts "Yeah #{favenum} is nice enough but #{better} is bigger and better by far!"

回答by user1475867

Try using string interpolation, like this:

尝试使用字符串插值,如下所示:

puts "Yeah #{favenum} is nice enough but #{better} is bigger and better by far! Think on."

回答by Lachlan Hardy

Based on the tutorial you're following

根据您正在关注的教程

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.'

Produces the "correct" result at a beginner level.

在初学者级别产生“正确”的结果。