String concatenation in Rails 3

流过昼夜 提交于 2019-12-04 04:27:12

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

If you explicitly include the parenthesis at the end of the to_s method call the problem goes away:

> params['controller'].to_s() +'/'
=> "posts/"

If you want to concatenate a string, the safest way is to write "#{params[:controller].to_s} /" ruby's string escaping is safer and better in many cases

Look closely the error:

p "hi".to_s +'/'
p "hi".to_s -'2'

#=> in `<main>': undefined method `+@' for "/":String (NoMethodError)

This is because unary operator +,- etc is defined only Numeric class objects. It will be clear if you look at the code below:

p "hi".to_s +2
#=>in `to_s': wrong number of arguments (1 for 0) (ArgumentError)

Now the above error is exactly right for to_s. As to_s doesn't take any argument when it is called.

Correct version is:

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