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

时间:2015-04-24 19:35:13

标签: 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>,
  <OpenStruct percent=73, type=1>,
  <OpenStruct percent=64, type=1>,
  <OpenStruct percent=74, type=2>
]ect

我怎样才能做到这一点?目前我只能按类型降序排序。

array = array.sort_by {|r| r.type }

1 个答案:

答案 0 :(得分:3)

这应该这样做:

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>