Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I want to expand on this a bit:</p> <pre><code>array = [].tap { |ary| ary &lt;&lt; 5 if something } </code></pre> <p>What this does (assuming <code>something</code> is true-ish):</p> <ol> <li><p>assigns <code>array</code> to <code>[]</code>, an empty array. </p> <pre><code>array.object_id = 2152428060 </code></pre></li> <li><p>passes <code>[]</code> to the block as <code>ary</code>. <code>ary</code> and <code>array</code> are pointing to the same array object. </p> <pre><code>array.object_id = 2152428060 ary.object_id = 2152428060 </code></pre></li> <li><p><code>ary &lt;&lt; 5</code> &lt;&lt; is a mutative method, meaning it will modify the receiving object. It is similar to the idiom of appending <code>!</code> to a method call, meaning "modify this in place!", like in <code>.map</code> vs <code>.map!</code> (though the bang does not hold any intrinsic meaning on its own in a method name). <code>ary</code> has 5 inserted, so <code>ary</code> = <code>array</code> = <code>[5]</code></p> <pre><code>array.object_id = 2152428060 ary.object_id = 2152428060 </code></pre></li> </ol> <p>We end with <code>array</code> being equal to <code>[5]</code></p> <p>In the second example:</p> <pre><code>array = [].tap{ |ary| ary += [5] if something } </code></pre> <ol> <li>same</li> <li>same</li> <li><p><code>ary += 5</code> <code>+=</code> is short for <code>ary = ary + 5</code>, so it is first modification (<code>+</code>) and then assignment (<code>=</code>), in that order. It gives the appearance of modifying an object in place, but it actually does not. It creates an entirely new object.</p> <pre><code>array.object_id = 2152428060 ary.object_id = 2152322420 </code></pre></li> </ol> <p>So we end with <code>array</code> as the original object, an empty array with <code>object_id=2152428060</code> , and <code>ary</code>, an array with one item containing 5 with <code>object_id = 2152322420</code>. Nothing happens to <code>ary</code> after this. It is uninvolved with the original assignment of <code>array</code>, that has already happened. Tap executes the block after <code>array</code> has been assigned.</p>
    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.
 

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