2016-09-08 55 views
1

目前正在研究Ruby中的HackerRank问题。当我尝试编译:字符串不能被强制转换为Fixnum(TypeError)

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. 
+0

5行,你分配一个'String'它。所以,当然,这是一个'字符串'! –

回答

3

必须调用方法.to_s你的整数/浮动,如果你想将其添加到一些字符串

例如:或

i = 3 
b = ' bah ' 

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

,如果您有字符串是这样的:“3” ,并且您希望从此字符串整数中获得,如果您需要迭代器,则必须调用to_i方法,to_f它要浮点数

for example乐:

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

您还必须在'+'之前调用此对象上的'.to_s' –

2

double是由于gets.chomp

2

您已经定义double两次的字符串:

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

所以,Stringdouble已覆盖Float类型。

您已经定义:

d = 4.0 #Float type 

所以,当你这样做:以上

print d + double #actually you are doing here (Float + String) 
相关问题