如何按两个条件对红宝石数组进行排序 [英] How to sort a ruby array by two conditions
本文介绍了如何按两个条件对红宝石数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按两个不同的条件对该数组进行排序.
I want to sort this array by two different conditionals.
首先,我想按类型对数组进行排序:类型可以是(1,2,3,4),我想按4-1-2-3的顺序对其进行排序.
First I want to sort the array by type: A type can be either (1,2,3,4) and I want to sort them in this order 4 - 1 - 2 - 3.
然后在每种不同的类型中,我想按降序对它们进行排序.
Then within each different type I want to sort them by a percentage descending.
所以排序后的数组看起来像这样:
So a sorted array would look like this:
[
<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
如何完成这种排序?目前,我只能按降序排序.
How can I accomplish this sort? Currently I can only sort by type descending.
array = array.sort_by {|r| r.type }
推荐答案
这应该做到:
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>
这篇关于如何按两个条件对红宝石数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文