I have a mulitdimensional array like so:
[
[name, age, date, gender]
[name, age, date, gender]
[..]
]
I\'m wondering the best way to sort
This should do the trick:
array.sort { |a,b| [ a[1], a[0] ] <=> [ b[1], b[0] ] }
So what does this do? It uses a lot of Ruby idioms.
sort
method of Array uses them to compare two elements based on the return value of the block. You can read all about them here.<=>
operator. It returns -1 if the first argument is less than the second, 0 if they are equal, and 1 if the first is greater than the second. When you use it with arrays, it will compare the arrays element-wise until one of them returns -1 or 1. If the arrays are equal, you will get 0.