Ruby on Rails sort_by vs sort

Posted on 05 February 2010

Given the choice when sorting arrays in Ruby it's typically better to use sort_by rather than sort.

sort_by uses the Schwartzian transform technique that is a Perl programming idiom used to improve the efficiency of sorting a list of items.

You can use sort_by like so...

foo.sort_by(&:bar)

The equivalent using sort would look like...

foo.sort{|a,b| b.bar <=> a.bar}

However, using sort will mean that the method bar is called twice for each comparison and therein lies the inefficiency.

Got something to say?