Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String concatenation in Rails 3

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
like image 994
valk Avatar asked Apr 07 '13 15:04

valk


1 Answers

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/"
like image 150
Matt Glover Avatar answered Oct 04 '22 15:10

Matt Glover