Sorting: Sort array based on multiple conditions in Ruby

后端 未结 3 1017
不思量自难忘°
不思量自难忘° 2021-02-01 05:09

I have a mulitdimensional array like so:

[
  [name, age, date, gender]
  [name, age, date, gender]
  [..]
]

I\'m wondering the best way to sort

3条回答
  •  长发绾君心
    2021-02-01 05:43

    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.

    • First is blocks, which are sort of like callbacks or anonymous functions/classes in other languages. The 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.
    • Next is the <=> 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.

提交回复
热议问题