2016-09-08 7 views
1

現在、RubyのHackerRankの問題に取り組んでいます。私は、これらの二つの変数はいずれも文字列ではありませんので、私は理解していない次の行in `+ ':文字列をFixnum(TypeError)に強制することはできません

print d + double 

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

をコンパイルしようとします。

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'を割り当てます。もちろん、それは 'String'です! –

答えて

3

あなたは、たとえば、何かの文字列

に追加したい場合は、あなたの整数/浮動小数点数にメソッド.to_sを呼び出す必要があります:

i = 3 
b = ' bah ' 

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

か、このような文字列を持っている場合:「3」あなたがこの文字列整数から取得したい場合は、to_f浮動小数点数を指定したい場合は、to_iメソッドを呼び出す必要があります。

exampル:

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

'+'の前にこのオブジェクトの '.to_s'も呼び出さなければなりません –

2

doubleあなたはdouble 2回定義されているため、gets.chomp

2

に文字列です:だから

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

を、StringタイプのdoubleFloatタイプをオーバーライドしています。あなたが定義されている

d = 4.0 #Float type 

をだからあなたが行うとき:上記

print d + double #actually you are doing here (Float + String) 
関連する問題