字符串连接错误
我遇到了语法错误。我承认这是一个语法错误,但我有点好奇为什么这是一个语法错误。
这完全按照你的预期工作:
(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 似乎没有问题,但如果第一个加号碰巧触及双引号,我收到语法错误。
究竟为什么会发生这种情况?
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.
This works exactly as you'd expect it to:
(0..9).each { |n| puts n.to_s + "^2 = " + (n**2).to_s }
This throws an error:
(0..9).each { |n| puts n.to_s +"^2 = "+ (n**2).to_s }
The error:
NoMethodError: undefined method '+@' for "^2 = ":String
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.
Why exactly does this happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
n.to_s +"^2 = "
被解析为n.to_s(+"^2 = ")
,它在语法上是有效的,意思是“执行一元加运算”字符串^2 =
上,然后将结果作为参数传递给to_s
”。但是,由于字符串没有一元加法运算(由+@
方法表示),因此您会收到NoMethodError
(不是语法错误)。以这种方式解析而不是
n.to_s() + "^2 = "
的原因是,如果以这种方式解析,则puts +5
或puts -x
还必须解析为puts() + 5
和puts() - x
而不是puts(+5)
和puts(-x) - 在该示例中很明显后者就是我们的意图。n.to_s +"^2 = "
is parsed asn.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 toto_s
". However since strings don't have a unary plus operation (represented by the method+@
), you get aNoMethodError
(not a syntax error).The reason that it's parsed this way and not as
n.to_s() + "^2 = "
is that if it were parsed this way thenputs +5
orputs -x
would also have to be parsed asputs() + 5
andputs() - x
rather thanputs(+5)
andputs(-x)
- and in that example it's rather clear that the latter is what was intended.