Possible Duplicate:
Sorting an array in descending order in Ruby可能重复:在Ruby中按降序对数组进行排序
I want to sort an array of elements based on some condition, except in reverse order. So basically whatever it would have done and then reversed.
我想根据某些条件对元素数组进行排序,但顺序相反。所以基本上无论它做什么然后逆转。
So for example I have an array of strings and I want to sort it by decreasing string length
所以例如我有一个字符串数组,我想通过减少字符串长度对它进行排序
a = ["test", "test2", "s"]
a.sort_by!{|str| str.length}.reverse!
While this does the job...is there a way to specify the condition such that the sorting algorithm will do it in reverse?
虽然这样做了......有没有办法指定条件,以便排序算法反过来做?
2 个解决方案
#1
21
The length is a number so you can simply negate it to reverse the order:
长度是一个数字,所以你可以简单地否定它来反转顺序:
a.sort_by! { |s| -s.length }
If you're sorting on something that isn't easily negated then you can use sort!
and manually reverse the comparison. For example, normally you'd do this:
如果你正在对不容易否定的事情进行排序,那么你可以使用排序!并手动反转比较。例如,通常你会这样做:
# shortest to longest
a.sort! { |a,b| a.length <=> b.length }
but you can swap the order to reverse the sorting:
但您可以交换订单以反转排序:
# longest to shortest
a.sort! { |a,b| b.length <=> a.length }
#2
6
The answer from @mu is too short is great, but only works for numbers. For the general case, you can resort to the sort
method:
@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"]
#1
21
The length is a number so you can simply negate it to reverse the order:
长度是一个数字,所以你可以简单地否定它来反转顺序:
a.sort_by! { |s| -s.length }
If you're sorting on something that isn't easily negated then you can use sort!
and manually reverse the comparison. For example, normally you'd do this:
如果你正在对不容易否定的事情进行排序,那么你可以使用排序!并手动反转比较。例如,通常你会这样做:
# shortest to longest
a.sort! { |a,b| a.length <=> b.length }
but you can swap the order to reverse the sorting:
但您可以交换订单以反转排序:
# longest to shortest
a.sort! { |a,b| b.length <=> a.length }
#2
6
The answer from @mu is too short is great, but only works for numbers. For the general case, you can resort to the sort
method:
@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"]