Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As the others pointed out, <code>||</code> first evaluates the expression on the left. If it is "true" (anything except <code>false</code> or <code>nil</code>), it returns that. Otherwise, it evaluates the expression on the right, and returns it (no matter what it is).</p> <p>This makes <code>||</code> useful for a lot more than just boolean tests. For example, I just used it the other day when writing some code for the <code>chronic</code> gem:</p> <pre><code>@now = options[:now] || Chronic.time_class.now </code></pre> <p>That means: "if the <code>options</code> hash includes a <code>:now</code> value, store that in <code>@now</code>. Otherwise, fall back on <code>Chronic.time_class.now</code> as a default". I'm sure you can think of lots of possible applications in your own programs.</p> <p><code>&amp;&amp;</code> is analogous: it first evaluates the expression on the left, and if it evaluates to <code>false</code> or <code>nil</code>, it returns that. Otherwise, it evaluates the expression on the right, and returns it (no matter what it is).</p> <p>This means <code>&amp;&amp;</code> is <em>also</em> useful for a lot more than just boolean tests. You can use it to squeeze two lines of code into one. For example:</p> <pre><code>do_something &amp;&amp; do_something_else </code></pre> <p>(That only works if you know that the return value of <code>do_something</code> will never be <code>false</code> or <code>nil</code>!)</p> <p>You can also use <code>&amp;&amp;</code> to squeeze a "guard" expression on the same line as what it is "guarding":</p> <pre><code>message &amp;&amp; send_message(message) </code></pre> <p>Which could replace:</p> <pre><code>unless message.nil? send_message(message) end </code></pre>
    singulars
    1. This table or related slice is empty.
    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