ruby 字符串不能被强制转换为 Fixnum (TypeError)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25397484/
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
String can't be coerced into Fixnum (TypeError)
提问by theodora nortey
I wrote the basic codes below
我写了下面的基本代码
puts ' Hi there , what is your favorite number ? '
number = gets.chomp
puts number + ' is beautiful '
puts 1 + number.to_i + 'is way better'
But when I run it,I get the error "String can't be coerced into Fixnum (TypeError)". How do I correct this error please?
但是当我运行它时,我收到错误“字符串不能被强制转换为 Fixnum (TypeError)”。请问这个错误怎么改?
回答by Uri Agassi
You cannot add a String to a number. You canadd a number to a String, since it is coerced to a String:
您不能将字符串添加到数字。您可以将数字添加到字符串,因为它被强制转换为字符串:
'1' + 1
# => "11"
1 + 1
# => 2
1 + '1'
# TypeError!
Since I suspect you want to show the result of adding 1 to your number, you should explicitly cast it to string:
由于我怀疑您想显示将 1 添加到您的数字的结果,您应该将其显式转换为 string:
puts (1 + number.to_i).to_s + ' is way better'
or, use string interpolation:
或者,使用字符串插值:
puts "#{1 + number.to_i} is way better"
回答by Yoseph.B
String can't be coerced into Integerusually happens, when you try to add a string to a number. since you want to add 1 to your number and concatenate it with a string "is way better". you have to explicitly cast the result you got from adding 1 to your number to a string and concatenate it with your string "is way better".
当您尝试将字符串添加到数字时,通常会发生字符串无法强制转换为 Integer 的情况。因为你想在你的数字上加 1 并将它与一个字符串连接起来“更好”。您必须将数字加 1 得到的结果显式转换为字符串,并将其与字符串连接起来“更好”。
you can update your code to this:
您可以将代码更新为:
puts (1 + number.to_i).to_s + " " + 'is way better'
回答by Steve Wilhelm
You might find the results of entering 'xyz' as an input surprising.
您可能会发现输入 'xyz' 作为输入的结果令人惊讶。
This discussionfor determining if your input string is a number may be helpful.
这种讨论确定,如果您的输入字符串是一个数字可能会有所帮助。
回答by sawa
Assuming that the numbers are natural numbers:
假设这些数是自然数:
number = gets.chomp
puts "#{number} is beautiful ", "#{number.succ} is way better"

