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.

About Paul

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Comments...

  • Thanks for the straightforward explanation! It was useful to me.

    Evan at 18 Feb 11 at 15:20

  • When I try to use sort_by:

    "NoMethodError: You have a nil object when you didn't expect it!
    You might have expected an instance of Array.
    The error occurred while evaluating nil.<=>
    from (irb):42:in `sort_by'
    from (irb):42"

    What I doing wrong?

    Sergey at 18 Aug 11 at 11:21

  • Thanks Paul! I just used this and it was great! I've always hated all the lengthy syntax required for the normal sort method.

    Ammar Yousuf at 02 Nov 11 at 18:24

  • Thanks. Was helpful.

    A Person at 06 Dec 11 at 10:52

Got something to say?