Thankfully, #ruby-lang was very helpful (and confirmed that the docs were lacking here).
Let's say you want to sort this array of arrays:
a = [[1,2,3],[1,0,2],[2,3,2]]
and you want to sort by both the 0 and 1 indexes of the inner arrays.
You can write this:
You will get this:
The sort_by method is used when it's costly to do the comparison itself (for instance, if you need to sort File objects, which are costly to create during a normal call to
sort_bycreates another enumeration of keys, one for every element in your array to be sorted. In the above example, we are relying on the fact that Array implements the
<&eq;>method. So we are creating a new array which contains the multiple elements corresponding to our multiple conditions.
Note that this trick of creating an array of the sortable values will work just fine in