在Ruby on Rails中对数组进行排序

时间:2014-03-12 11:51:50

标签: ruby-on-rails ruby arrays sorting

arr = [
  [0, "Moving Companies", 10],
  [0, "ab-thera-sensa", 5],
  [0, "belt-center", 16],
  [0, "isabel", 3],
  [0, "kreatio", 2],
  [0, "service1", 7],
  [0, "sorbion-sachet-multi-star", 6],
  [0, "sss", 15],
  [0, "telecom-service-industry", 14],
  [1, " AbsoPad", 13],
  [1, "telecom-service", 8],
  [2, "cutisorb-ultra", 12],
  [2, "sorbion-contact", 11],
  [2, "sorbion-sachet-multi-star", 9]
]

假设这是我的数组,现在我想根据第一个元素按降序排序。我可以做arr.sort.reverse但问题现在就开始了

我把数组作为:

[
    [2, "sorbion-sachet-multi-star", 9],
    [2, "sorbion-contact", 11],
    [2, "cutisorb-ultra", 12],
    [1, "telecom-service", 8],
    [1, " AbsoPad", 13],
    [0, "telecom-service-industry", 14],
    [0, "sss", 15], [0, "sorbion-sachet-multi-star", 6],
    [0, "service1", 7],
    [0, "kreatio", 2],
    [0, "isabel", 3],
    [0, "belt-center", 16],
    [0, "ab-thera-sensa", 5],
    [0, "Moving Companies", 10]
]

现在,数组应该按照第二个元素的升序排序。

如何实现?

结果如下:

[
  [2, "cutisorb-ultra", 12],
  [2, "sorbion-contact", 11],
  [2, "sorbion-sachet-multi-star", 9],
  [1,.......]
]

3 个答案:

答案 0 :(得分:2)

使用块自定义排序。首先按第一个元素(0)进行降序排序。如果它们相等,则由第二个元素(1)进行升序排序:

arr.sort! do |a, b|
  result = b[0] <=> a[0]
  result = a[1] <=> b[1] if result == 0
  result
end

答案 1 :(得分:0)

这个怎么样?

arr.sort { |i,j| [j[0],j[2]] <=> [i[0],i[2]]  }

输出:

=> [[2, "cutisorb-ultra", 12],
 [2, "sorbion-contact", 11],
 [2, "sorbion-sachet-multi-star", 9],
 [1, " AbsoPad", 13],
 [1, "telecom-service", 8],
 [0, "belt-center", 16],
 [0, "sss", 15],
 [0, "telecom-service-industry", 14],
 [0, "Moving Companies", 10],
 [0, "service1", 7],
 [0, "sorbion-sachet-multi-star", 6],
 [0, "ab-thera-sensa", 5],
 [0, "isabel", 3],
 [0, "kreatio", 2]]

答案 2 :(得分:-1)

请尝试:

arr.sort_by{|x|[-x[0],-x[2]]}