Sorting by multiple columns in Ruby

From EggeWiki
Revision as of 23:18, 8 October 2009 by Brianegge (talk | contribs) (Created page with '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 …')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.