Reputation: 7708
On ruby 1.8.7
Why this is ok:
string += method "value"
But this raise a syntax error:
string << method "remove reviewer"
Is the same behaviour in newer versions of ruby?
Upvotes: 0
Views: 50
Reputation: 34318
Yeah, same behaviour in the higher version of Ruby as well. (I tested on Ruby 2.2).
It's because of Ruby's operator precedence.
To get around this, you can use parentheses in case of <<
:
string << method("remove reviewer")
Then, it should work and won't get the syntax error.
Or, to make it consistent, you can use parentheses for both of them:
string += method("value")
string << method("remove reviewer")
Infact, it is highly recommended to use parentheses ()
for method calls to avoid such situations like the one you're asking about. Check this post for some more information.
Upvotes: 1
Reputation: 106802
You can explain this behaviour with the different Operator Precedence of <<
and =+
and method calls.
Ruby reads your first examples as:
string += (method "value")
but the second one as:
(string << method) "remove reviewer"
IMO it is a good practice to use parenthesize for method call even if Ruby does not need them in many case. This makes the code more readable and less error-prone:
string += method("value")
string << method("remove reviewer")
Upvotes: 1