字符串串联错误 [英] String Concatenation Error
问题描述
我遇到语法错误.我接受这是一个语法错误,但是对于为什么这是一个语法错误,我有点好奇.
I ran into a syntax error. I accept that it's a syntax error, but I'm somewhat curious as to why it's a syntax error.
这完全符合您的预期:
(0..9).each { |n| puts n.to_s + "^2 = " + (n**2).to_s }
这会引发错误:
(0..9).each { |n| puts n.to_s +"^2 = "+ (n**2).to_s }
错误:
NoMethodError: undefined method '+@' for "^2 = ":String
奇怪的是,我可以将第二个加号移动到任何地方,而Ruby似乎对此没有问题,但是如果第一个加号碰到双引号,则会出现语法错误.
Oddly, I can move the second plus sign wherever and Ruby seems to have no problem with it, but if that first one happens to touch the double quote, I get a syntax error.
为什么会这样呢?
推荐答案
n.to_s +"^2 = "
解析为n.to_s(+"^2 = ")
,这在语法上是有效的,并且意味着对字符串^2 =
执行一元加号操作,然后传递结果作为to_s
的参数".但是,由于字符串没有一元加号操作(由方法+@
表示),您会得到NoMethodError
( not 语法错误).
n.to_s +"^2 = "
is parsed as n.to_s(+"^2 = ")
, which is syntactically valid and means "perform the unary plus operations on the string ^2 =
and then pass the result as an argument to to_s
". However since strings don't have a unary plus operation (represented by the method +@
), you get a NoMethodError
(not a syntax error).
以这种方式而不是以n.to_s() + "^2 = "
进行解析的原因是,如果以这种方式进行解析,则puts +5
或puts -x
也必须被解析为puts() + 5
和puts() - x
而不是puts(-x)
-在该示例中,很明显后者是预期的.
The reason that it's parsed this way and not as n.to_s() + "^2 = "
is that if it were parsed this way then puts +5
or puts -x
would also have to be parsed as puts() + 5
and puts() - x
rather than puts(+5)
and puts(-x)
- and in that example it's rather clear that the latter is what was intended.
这篇关于字符串串联错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!