What's the precedence of ruby's method call

Any operator has precedence over the method call. It is highly recommended to use () for method calls to avoid situations like the one you're asking about.


Ruby method invocation has a lower precedence than any of the operators, but that's not the full story - there are some edge cases that are nonobvious. Your question got me curious about one of them, so I asked on the ruby-talk mailing list. You should find the resulting thread helpful.

Also, read this blog post for a good argument that you should use parentheses liberally, especially while you are learning ruby.


We can use your Programming Ruby link as a starting point and discover for ourselves where unparenthesized method-calls belong in the precedence table. I'm only going to show the final tests that pinpoint the location.

It's lower than defined?:

defined? Math.sqrt 2
# => SyntaxError: unexpected tINTEGER, expecting end-of-input

Aha, it's higher than not:

not Math.sqrt 2
=> false

Now you know exactly when you should use parentheses.

Sidenote

(thanks to Martin Demello's link to ruby-talk for reminding me)

Keep in mind that the operators in the table only apply when not being used in the method-call syntax. Example - the following doesn't obey the rules for * and + because they're not being used as operators, but methods:

# This happens because unparenthesized method calls are right-associative.
2.* 5.+ 2  # => 14

If that looks confusing, the same thing is happening here:

# The `modulo` is evaluated first because it's on the right
Math.sqrt 9.modulo 5