Rails 3中的字符串串联 [英] String concatenation in Rails 3
本文介绍了Rails 3中的字符串串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道为什么会这样:如果加号和下一个字符串之间有空格,则Ruby将两个字符串连接起来。但是如果没有空间,是否会应用一元运算符?
I'm wondering why this is so: Ruby concatenates two strings if there is a space between the plus and the next string. But if there is no space, does it apply some unary operator?
params['controller'].to_s + '/'
# => "posts/"
params['controller'].to_s +'/'
# => NoMethodError: undefined method `+@' for "/":String
推荐答案
解析器将 +'/'
解释为 to_s
方法调用的第一个参数。它将这两个语句视为等效:
The parser is interpreting +'/'
as the first parameter to the to_s
method call. It is treating these two statements as equivalent:
> params['controller'].to_s +'/'
# NoMethodError: undefined method `+@' for "/":String
> params['controller'].to_s(+'/')
# NoMethodError: undefined method `+@' for "/":String
如果在 to_s
方法调用的末尾显式包括括号,则问题将消失:
If you explicitly include the parenthesis at the end of the to_s
method call the problem goes away:
> params['controller'].to_s() +'/'
=> "posts/"
这篇关于Rails 3中的字符串串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文