String Concatenation Error

前端 未结 1 1429
终归单人心
终归单人心 2021-02-15 13:36

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

相关标签:
1条回答
  • 2021-02-15 14:03

    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.

    0 讨论(0)
提交回复
热议问题