Tom Lehman
Tom Lehman

Reputation: 89203

Sorting an array by two values

Suppose I have

an_array = [[2, 3], [1, 4], [1, 3], [2, 1], [1, 2]]

I want to sort this array by the first value of each inner array, and then by the second (so the sorted array should look like this: [[1, 2], [1, 3], [1, 4], [2, 1], [2, 3]])

What's the most readable way to do this?

Upvotes: 8

Views: 1749

Answers (3)

Marcelo Cantos
Marcelo Cantos

Reputation: 185842

an_array.sort

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246764

If you want some non-default behaviour, investigate sort_by (ruby 1.8.7+)

e.g. sort by the second element then by the first

a.sort_by {|e| [e[1], e[0]]}  # => [[2, 1], [1, 2], [1, 3], [2, 3], [1, 4]]

or sort by the first element ascending and then the second element descending

a.sort_by {|e| [e[0], -e[1]]}  # => [[1, 4], [1, 3], [1, 2], [2, 3], [2, 1]]

Upvotes: 9

Alex Reisner
Alex Reisner

Reputation: 29427

This is the default behavior for sorting arrays (see the Array#<=> method definition for proof). You should just be able to do:

 an_array.sort

Upvotes: 13

Related Questions