Sorting By Multiple Conditions in Ruby

I recently had to sort by multiple conditions in Ruby, and had a hard time coming up with the Ruby way to do this. The Ruby Docs didn't have what I was looking for, either.

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:

a.sort_by{|e| [e[0],e[1]]}

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).

sort_by creates 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 sort.

Popular posts from this blog

Lists and arrays in Dart

Converting Array to List in Scala

The 29 Healthiest Foods on the Planet