2015-04-24 69 views
2

我想按兩個不同的條件排序此數組。如何按兩個條件排序紅寶石數組

首先我想按類型對數組進行排序:A型可以是(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 } 
+0

爲什麼你要4先來嗎?重新命名類型並將4更改爲1,如果4應該始終先出現,是否有意義? –

回答

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> 
+1

不要爲此使用'sort'。它會比使用'sort_by'的實現慢得多。請參閱http://stackoverflow.com/a/2651028/128421並比較相同的'sort'和'sort_by'測試。 –