String Concatenation Error

老子叫甜甜 提交于 2019-12-09 10:11:49

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/5861693/string-concatenation-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!