String Concatenation in Rails 3

I wonder why this is so: Ruby concatenates two lines if there is a space between the plus and the next line. But if there is no space, is it applicable to some unary operator?

params['controller'].to_s + '/' # => "posts/" params['controller'].to_s +'/' # => NoMethodError: undefined method ` +@ ' for "/":String 
+7
source share
3 answers

The analyzer interprets +'/' as the first parameter to call the to_s method. He considers 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 brackets at the end of the to_s method to_s , the problem goes away:

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

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

+6
source

Look carefully at the error:

 p "hi".to_s +'/' p "hi".to_s -'2' #=> in `<main>': undefined method ` +@ ' for "/":String (NoMethodError) 

This is because unary operator + , - , etc. defined only by objects of the Numeric class. 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 exactly matches to_s . Since to_s does not accept any arguments when called.

The correct version is:

 p "hi".to_s + '2' #=> "hi2" 
+4
source

All Articles