如何按两个条件对ruby数组进行排序

如何按两个条件对ruby数组进行排序,ruby,arrays,sorting,Ruby,Arrays,Sorting,我想用两个不同的条件对这个数组进行排序 首先,我想按类型对数组进行排序:类型可以是(1,2,3,4),我想按4-1-2-3的顺序对它们进行排序 然后在每个不同的类型中,我想按百分比降序对它们进行排序 因此,排序后的数组如下所示: [ <OpenStruct percent=70, type=4>, <OpenStruct percent=60, type=4>, <OpenStruct percent=50, type=4>, <Open

我想用两个不同的条件对这个数组进行排序

首先,我想按类型对数组进行排序:类型可以是(1,2,3,4),我想按4-1-2-3的顺序对它们进行排序

然后在每个不同的类型中,我想按百分比降序对它们进行排序

因此,排序后的数组如下所示:

[
  <OpenStruct percent=70, type=4>,
  <OpenStruct percent=60, type=4>,
  <OpenStruct percent=50, type=4>,
  <OpenStruct percent=73, type=1>,
  <OpenStruct percent=64, type=1>,
  <OpenStruct percent=74, type=2>
]ect
这应该做到:

require 'ostruct'
arr = [
  OpenStruct.new(percent: 73, type: 1),
  OpenStruct.new(percent: 70, type: 4),
  OpenStruct.new(percent: 60, type: 4),
  OpenStruct.new(percent: 50, type: 4),
  OpenStruct.new(percent: 64, type: 1),
  OpenStruct.new(percent: 74, type: 2)
]


puts arr.sort_by { |a| [a.type % 4, -a.percent] }
输出:

#<OpenStruct percent=70, type=4>
#<OpenStruct percent=60, type=4>
#<OpenStruct percent=50, type=4>
#<OpenStruct percent=73, type=1>
#<OpenStruct percent=64, type=1>
#<OpenStruct percent=74, type=2>
#
#
#
#
#
#

为什么你想让4先走?如果4总是先到,那么重命名类型并将4更改为1有意义吗?不要为此使用
sort
。它将比使用
sort\u by
的实现慢得多。请参阅并比较等效的
sort
sort\u by
测试。
#<OpenStruct percent=70, type=4>
#<OpenStruct percent=60, type=4>
#<OpenStruct percent=50, type=4>
#<OpenStruct percent=73, type=1>
#<OpenStruct percent=64, type=1>
#<OpenStruct percent=74, type=2>