2016-09-08 87 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) 
相關問題