Ruby Flare

Your awesome Tagline

0 notes

Sort vs sort_by

I always forget the difference between Ruby’s sort and sort_by methods. In a nutshell:

sort

  • can be used with or without a block
  • the block takes two arguments
  • inside the block you need to use the <=> operator

sort_by

  • can only be used with a block
  • the block takes only one argument

Generally, you’ll want to use the sort_by method unless your list is a simple one.

What I will use to help me remember is: sort_by what (1 argument) and sort what and what (2 arguments).

Examples:

[1,3,9,2].sort
[1,3,9,2].sort { |a,b| b <=> a }

%w{ abcd ab abc abcde }.sort_by { |i| i.length }
candidates.sort_by { |c| candidates.last_name }

(Source: brandon.dimcheff.com)

Filed under ruby sorting