7

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

3 Answers 3

9

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/"
Sign up to request clarification or add additional context in comments.

1 Comment

no undefined method `+@' for "/":String not for your explanations.
6

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

1 Comment

safer is the kicker!
4

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.