tags:

views:

113

answers:

3

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?

+1  A: 

an_array.sort

Marcelo Cantos
+11  A: 

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
Alex Reisner
+2  A: 

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]]
glenn jackman
@glenn jackman: great answer!!! that's what I was looking for. thank you
Radek