rornoob.com >

Sort it out - quick guide to ruby sort



11-Dec-2009

Everyone knows how easy it is to sort an array in ruby right? Just use the sort method.

But what about when you need to sort an array of objects? Sort no longer works on the array as a whole - how would it know which attribute you want to sort by? Luckily, sorting arrays with objects and sorting on multiple attributes is still a breeze.

Let's say we have a collection of reports, where each report has a title, a price and a priority.

  reports = Reports.find(:all)

See how simple it is sort by any one or more of the report attributes!

simple sort

  cheapest_first = reports.sort { |a,b| a.price <=> b.price }

reverse sort

  dearest_first = reports.sort { |a,b| b.price <=> a.price }

sort by multiple attributes

  prioritised_reports = reports.sort { |a,b| [a.priority, b.price] <=> [b.priority, a.price] }

sort and overwrite the existing array

  reports.sort! { |a,b| a.price <=> b.price }

sort, while ignoring capitalisation

  reports.sort! { |a,b| a.title.downcase <=> b.title.downcase }

Of course ruby on rails also makes it easy to get your object collection pre-sorted by the database, that's probably faster in many cases but can't always be done (e.g. if you're working on an array of objects that's already had a bunch of filtering applied.)

rails db sort

  cheapest_three_reports = Reports.find(:all, :order=>:price, :limit=>3)

I'm sure that much more is possible, but the simple examples above show just how easy it is to sort through arrays in ruby on rails.

| |

del.icio.usDiggblogmarksNewsvineStumbleUponTechnoratiFurlReddit

Add your comment
Name
Website
Heading
Comment