Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>a ||= b</code> is a "conditional assignment operator". It is <em>sort-of-but-not-quite</em>(*) shorthand for <code>a || a = b</code>.</p> <p>It means "<strong>if <code>a</code> is undefined or <a href="https://gist.github.com/jfarmer/2647362" rel="noreferrer">falsey</a> (<code>false</code> or <code>nil</code>), then evaluate <code>b</code> and set <code>a</code> to the result</strong>".</p> <p>For example:</p> <pre><code>&gt; a ||= nil =&gt; nil &gt; a ||= 0; =&gt; 0 &gt; a ||= 2; =&gt; 0 &gt; foo = false; =&gt; false &gt; foo ||= true; =&gt; true &gt; foo ||= false; =&gt; true </code></pre> <p>Ruby's short circuit evaluation means that if <code>a</code> is defined and evaluates to truthy, then the right hand side of the operator is not evaluated, and no assignment takes place. This distinction is unimportant if <code>a</code> and <code>b</code> are both local variables, but is significant if either is a getter/setter method of a class.</p> <p>Confusingly, it looks similar to other assignment operators (such as <code>+=</code>) but behaves differently.</p> <p><code>a += b</code> &nbsp;&nbsp;translates to&nbsp;&nbsp; <code>a = a + b</code></p> <p><code>a ||= b</code> &nbsp;&nbsp;roughly translates to* &nbsp;&nbsp; <code>a || a = b</code></p> <p>*Except that, when <code>a</code> is undefined, <code>a || a = b</code> would be NameError, whereas <code>a ||= b</code> sets <code>a</code> to <code>b</code>.</p> <p>Further reading:</p> <ul> <li><a href="http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html" rel="noreferrer">http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html</a></li> </ul>
    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