DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Call Sort With A Block

05.30.2006
| 12242 views |
  • submit to reddit
        From http://practicalruby.blogspot.com/2006/05/call-sort-with-block.html:

I needed to sort a list of partners today so I added:
class Partner
  def <=>(other)
     self.name <=> other.name
  end
end
However, I could have just done:
Partner.find(:all).sort { |one, other| one.name <=> other.name }
Doc for <a href="http://ruby-doc.org/core/classes/Array.html#M000424">sort</a> here.

From Comments:
You could also have used sort_by as long as the target supports the spaceship operator. ie:
Partner.find(:all).sort_by { |partner| partner.name }
With active_support required (or 'facet/symbol/to_proc' from the facets library) you can even:
Partner.find(:all).sort_by(&:name)

Sweet.