目前正在研究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.发布于 2016-09-08 17:01:41
如果要将整数/浮点数添加到字符串中,则必须调用方法.to_s
例如:
i = 3
b = ' bah '
c = i.to_s + b
# => '3 bah'或者,如果您有这样的字符串:'3',并且您想从这个字符串整数中获取,您必须调用to_i方法,如果您想要iteger,那么to_f它是您想要浮动的。
例如:
i = '3'
g = i.to_f
# => 3发布于 2016-09-08 17:07:43
您已经定义了double两次:
double = 4.0 #Float type
double = gets.chomp #String type因此,double of String类型已经重写了Float类型。
你的定义是:
d = 4.0 #Float type所以当你这么做的时候
print d + double #actually you are doing here (Float + String)发布于 2016-09-08 17:02:13
double是gets.chomp的字符串
https://stackoverflow.com/questions/39396533
复制相似问题