Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array by two values

Tags:

ruby

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?

like image 663
Tom Lehman Avatar asked Jan 27 '10 01:01

Tom Lehman


1 Answers

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
like image 125
Alex Reisner Avatar answered Oct 09 '22 09:10

Alex Reisner