首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在“+”中:不能强迫字符串进入Fixnum (TypeError)

在“+”中:不能强迫字符串进入Fixnum (TypeError)
EN

Stack Overflow用户
提问于 2016-09-08 16:58:06
回答 3查看 2.8K关注 0票数 1

目前正在研究Ruby中的HackerRank问题。当我试图编译

代码语言:javascript
运行
复制
in `+': String can't be coerced into Fixnum (TypeError) 

在下面这一行

代码语言:javascript
运行
复制
print  d + double

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

代码语言:javascript
运行
复制
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.
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-09-08 17:01:41

如果要将整数/浮点数添加到字符串中,则必须调用方法.to_s

例如:

代码语言:javascript
运行
复制
i = 3
b = ' bah '

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

或者,如果您有这样的字符串:'3',并且您想从这个字符串整数中获取,您必须调用to_i方法,如果您想要iteger,那么to_f它是您想要浮动的。

例如:

代码语言:javascript
运行
复制
i = '3'
g = i.to_f
# => 3
票数 4
EN

Stack Overflow用户

发布于 2016-09-08 17:07:43

您已经定义了double两次:

代码语言:javascript
运行
复制
double = 4.0  #Float type
double = gets.chomp #String type

因此,double of String类型已经重写了Float类型。

你的定义是:

代码语言:javascript
运行
复制
d = 4.0 #Float type

所以当你这么做的时候

代码语言:javascript
运行
复制
print d + double  #actually you are doing here (Float + String)
票数 4
EN

Stack Overflow用户

发布于 2016-09-08 17:02:13

doublegets.chomp的字符串

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39396533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档