Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In your example</p> <pre><code>a.sort </code></pre> <p>is equivalent to</p> <pre><code>a.sort { |x, y| x &lt;=&gt; y } </code></pre> <p>As you know, to sort an array, you need to be able to compare its elements (if you doubt that, just try to implement any sort algorithm without using any comparison, no <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code> or <code>&gt;=</code>).</p> <p>The block you provide is really a function which will be called by the <code>sort</code> algorithm to compare two items. <strong>That is <code>x</code> and <code>y</code> will always be some elements of the input array chosen by the <code>sort</code> algorithm during its execution.</strong></p> <p>The <code>sort</code> algorithm will assume that this comparison function/block will meet the requirements for method <code>&lt;=&gt;</code>:</p> <ul> <li>return -1 if x &lt; y</li> <li>return 0 if x = y</li> <li>return 1 if x > y</li> </ul> <p>Failure to provide an adequate comparison function/block will result in array whose order is undefined.</p> <p>You should now understand why</p> <pre><code>a.sort { |x, y| x &lt;=&gt; y } </code></pre> <p>and</p> <pre><code>a.sort { |x, y| y &lt;=&gt; x } </code></pre> <p>return the same array in opposite orders.</p> <hr/> <p>To elaborate on what Tate Johnson added, if you implement the comparison function <code>&lt;=&gt;</code> on any of your classes, you gain the following</p> <ol> <li>You may include the module <code>Comparable</code> in your class which will automatically define for you the following methods: <code>between?</code>, <code>==</code>, <code>&gt;=</code>, <code>&lt;</code>, <code>&lt;=</code> and <code>&gt;</code>.</li> <li>Instances of your class can now be sorted using the default (ie without argument) invocation to <code>sort</code>.</li> </ol> <p>Note that the <code>&lt;=&gt;</code> method is already provided wherever it makes sense in ruby's standard library (<code>Bignum</code>, <code>Array</code>, <code>File::Stat</code>, <code>Fixnum</code>, <code>String</code>, <code>Time</code>, etc...).</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. 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