在`+'中:字符串无法强制转换为Fixnum(TypeError)

时间:2016-09-08 16:58:07

标签: ruby-on-rails ruby rspec

目前正在处理Ruby中的HackerRank问题。当我尝试编译

in `+': String can't be coerced into Fixnum (TypeError) 

在以下一行

print  d + double

我不明白,因为这两个变量都不是字符串。

i = 4
d = 4.0
s = 'HackerRank'

# Declare second integer, double, and String variables.
intOne = 12
double = 4.0
string = "is the best place to learn and practice coding!, we get HackerRank is the best place to learn and practice coding!"

# Read and save an integer, double, and String to your variables.
intOne = gets.chomp
double = gets.chomp
string = gets.chomp
# Print the sum of both integer variables on a new line.
print i + intOne
# Print the sum of the double variables on a new line.
print d + double
# Concatenate and print the String variables on a new line
print s + string
# The 's' variable above should be printed first.

3 个答案:

答案 0 :(得分:3)

如果要将其添加到字符串

,则必须在整数/浮点数上调用方法.to_s

例如:

i = 3
b = ' bah '

c = i.to_s + b 
# => '3 bah'

或者如果您有这样的字符串:' 3',并且您希望从此字符串整数获取,如果您想要迭代,则必须调用to_i方法,to_f它是您想要的浮

例如:

i = '3'
g = i.to_f
# => 3

答案 1 :(得分:3)

您已定义double两次:

double = 4.0  #Float type
double = gets.chomp #String type

因此,double类型的String已覆盖Float类型。

您已定义:

d = 4.0 #Float type

所以当你这样做时:

print d + double  #actually you are doing here (Float + String)

答案 2 :(得分:2)

由于double

gets.chomp是一个字符串