Tuesday, October 30, 2007

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:


[[1,0,2],[1,2,3],[2,3,2]]


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.
Post a Comment

Disclaimer

I'm probably required to say that the views expressed in this blog are my own, and do not necessarily reflect those of my employer. Also, except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the BSD License.