字符串连接错误

发布于 2024-11-04 19:22:49 字数 439 浏览 3 评论 0原文

我遇到了语法错误。我承认这是一个语法错误,但我有点好奇为什么这是一个语法错误。

这完全按照你的预期工作:

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撧情箌佬 2024-11-11 19:22:49

n.to_s +"^2 = " 被解析为 n.to_s(+"^2 = "),它在语法上是有效的,意思是“执行一元加运算”字符串 ^2 = 上,然后将结果作为参数传递给 to_s”。但是,由于字符串没有一元加法运算(由 +@ 方法表示),因此您会收到 NoMethodError不是语法错误)。

以这种方式解析而不是 n.to_s() + "^2 = " 的原因是,如果以这种方式解析,则 puts +5puts -x 还必须解析为 puts() + 5puts() - x 而不是 puts(+5) 和puts(-x) - 在该示例中很明显后者就是我们的意图。

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).

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文