Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In Ruby any operator has precedence over method calls, e.g. operators are evaluated first.</p> <p>However the example <code>Math.sqrt 2 + 2</code> is a good illustration on how hard to read and unintuitive it can be to leave out parentheses. One might expect <code>Math.sqrt(2) + 2</code> to be evaluated here. </p> <p>When you come across a line like this, you might think: What did the coder intend? Is this a bug?</p> <p>It is always a good idea to use parentheses whenever you can, to make clear what you want, especially when there is a method call or multiple operators - it's just good style, and the lowest risk approach (e.g. don't make assumptions, but make yourself clear by using parentheses).</p> <p>It never hurts to add extra parentheses in expressions, but leaving them out can hurt quite a bit. </p> <p>Here's a nice example which I recently came across:</p> <pre><code> def foo(arg) raise "error" end x = foo 4 rescue 7 x =&gt; nil # oops! x = foo(4) rescue 7 x =&gt; 7 </code></pre> <p>I hope this nicely illustrates why it's important to use parentheses</p> <p><strong>Also:</strong></p> <p>Check here, under "Calling a Method" : <a href="http://ruby-doc.org/docs/ProgrammingRuby/html/tut_methods.html" rel="nofollow">http://ruby-doc.org/docs/ProgrammingRuby/html/tut_methods.html</a> Quote:</p> <blockquote> <p>[...] If there is no ambiguity you can omit the parentheses around the argument list when calling a method.[...] <strong>However, except in the simplest cases we don't recommend this</strong>---there are some subtle problems that can trip you up.[In particular, you must use parentheses on a method call that is itself a parameter to another method call (unless it is the last parameter).] <strong>Our rule is simple: if there's any doubt, use parentheses.</strong></p> </blockquote> <p>See also: <a href="http://phrogz.net/programmingruby/language.html" rel="nofollow">http://phrogz.net/programmingruby/language.html</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload