Sorting by multiple columns in Ruby

From EggeWiki
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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.