Sorting by multiple columns in Ruby

From EggeWiki
Jump to navigation Jump to search

In Ruby, it's quite easy to sort an array by a single column. For example:

<geshi lang="ruby> people.sort_by { |p| p.lastname } </geshi>

However, it's not clear how to easily sort by more than one column. Fortunately, there is a very easy way - simple put the columns you want into an array.

<geshi lang="ruby> people.sort_by { |p| [p.lastname, p.firstname] } </geshi>

This will handle nil values and any other corner cases perfectly.