String concatenation in Rails 3

霸气de小男生 提交于 2020-01-01 09:34:04

问题


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

回答1:


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/"



回答2:


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




回答3:


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"


来源:https://stackoverflow.com/questions/15864068/string-concatenation-in-rails-3

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