Never been to DZone Snippets before?

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

About this user

Matt Scilipoti

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

call sort with a block

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 sort 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.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS