I have a mulitdimensional array like so:
[
[name, age, date, gender]
[name, age, date, gender]
[..]
]
I’m wondering the best way to sort this array based on multiple conditions…For instance, how would I sort based on age first then by name?
I was messing around with the sort method like so:
array.sort { |a,b| [ a[1], a[0] ] <=> [ b[1], b[0] ] }
Besides that I don’t really understand this syntax, I’m not getting the results I would expect. Should I be using the sort method? Should I be individually comparing results by mapping the array?
You should always use
sort_byfor a keyed sort. Not only is it much more readable, it is also much more efficient. In addition, I would also prefer to use destructuring bind, again, for readability: