可能重複:
Sorting an array in descending order in Ruby紅寶石排序陣列以相反的順序
我要排序基於一些條件元件的陣列,除了以相反的順序。基本上,無論它會做什麼,然後扭轉。
所以,比如我有一個字符串數組,我想通過減少字符串長度
a = ["test", "test2", "s"]
a.sort_by!{|str| str.length}.reverse!
雖然這工作排序它...是否有指定使得分類條件的方式算法會做到相反?
可能重複:
Sorting an array in descending order in Ruby紅寶石排序陣列以相反的順序
我要排序基於一些條件元件的陣列,除了以相反的順序。基本上,無論它會做什麼,然後扭轉。
所以,比如我有一個字符串數組,我想通過減少字符串長度
a = ["test", "test2", "s"]
a.sort_by!{|str| str.length}.reverse!
雖然這工作排序它...是否有指定使得分類條件的方式算法會做到相反?
長度是一個數字,所以你可以簡單地否定它顛倒順序:
a.sort_by! { |s| -s.length }
如果你的東西,是不會輕易被否定,然後排序,你可以使用sort!
和手動反向的比較。例如,通常你可以這樣做:
# shortest to longest
a.sort! { |a,b| a.length <=> b.length }
,但你可以調換順序顛倒排序:
# longest to shortest
a.sort! { |a,b| b.length <=> a.length }
從@mu答案是太短是偉大的,但只適用於數字。對於一般情況,您可以使用sort
方法:
irb> a = ["foo", "foobar", "test"]
=> ["foo", "foobar", "test"]
irb> a.sort{|a,b| a.length <=> b.length}
=> ["foo", "test", "foobar"]
irb> a.sort{|a,b| b.length <=> a.length}
=> ["foobar", "test", "foo"]
哦,這是一個很好的把戲! – MxyL
+1輸入比我快:P – Thilo
性能明智,這是更好的(如果你問我更多的語義):'a.sort_by(&:length).reverse' – Mosselman