Note that there are some explanatory texts on larger screens.

plurals
  1. POIf || has higher precedence than =, then why does `a || a = b` work?
    text
    copied!<p>I understand the difference between <code>||</code> and <code>or</code>, or <code>&amp;&amp;</code> and <code>and</code>, but what I don't understand is this:</p> <p>Consider a method that returns the value of <code>@var</code>, or initializes it if <code>@var</code> is nil for false.</p> <p>As I came from JavaScript background, I would write it like this, since <code>||</code> has higher precedence than <code>=</code>:</p> <pre><code>def some_method @var || (@var = MyClass.new) end </code></pre> <p>or use <code>or</code>, since <code>or</code> has lower precedence:</p> <pre><code>def some_method @var or @var = MyClass.new end </code></pre> <p>or more concisely:</p> <pre><code>def some_method @var ||= MyClass.new end </code></pre> <p>But it so happened that this version <strong>also works</strong>:</p> <pre><code>def some_method @var || @var = MyClass.new end </code></pre> <p>I search the web but didn't find useful results.</p> <p>Most of them just tell the difference between <code>||</code> and <code>or</code>.</p> <p>The operator precedence table clearly says that <code>||</code> has higher precedence than <code>=</code>.</p> <p>I can even do <code>a = b || c = d</code> and Ruby sees it as <code>a = (b || (c = d))</code>.</p> <p>Is this behavior documented somewhere or is it some kind of magic in Ruby?</p> <p>P.S. CoffeeScript also has the same behavior.</p> <p><strong>Update / Clarification</strong>: This question is not about short-circuit evaluation. But about operator precedence. Please let me rephrase it again:</p> <p>If <code>||</code> has higher precedence than <code>=</code>, then why does ruby sees <code>a || a = b</code> as <code>a || (a = b)</code>, but not <code>(a || a) = b</code> and raise a syntax error?</p>
 

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