This question already has an answer here:
这个问题已经有了答案:
- reversing the order of an array in ruby 5 answers
- 在ruby 5中反转数组的顺序
I have an array:
我有一个数组:
a = [ 0,9,6,12,1]
I need a way to sort it in descending order:
我需要一种按降序排序的方法:
a = [12,9,6,1,0]
For sorting in ascending order I have a Ruby function a[].to_a.sort
, I'm looking for a function to sort the array in descending order.
为了按升序排序,我有一个Ruby函数a[].to_a。排序,我在找一个按降序排列数组的函数。
2 个解决方案
#1
10
do as below
做如下
a = [ 0,9,6,12,1]
sorted_ary = a.sort_by { |number| -number }
# or
sorted_ary = a.sort.reverse
update
更新
Another good way to do this :
另一个很好的方法是:
a.sort {|x,y| -(x <=> y)}
#2
0
You can do this:
你可以这样做:
[ 0,9,6,12,1].sort_by do |sort|
-sort
end
#1
10
do as below
做如下
a = [ 0,9,6,12,1]
sorted_ary = a.sort_by { |number| -number }
# or
sorted_ary = a.sort.reverse
update
更新
Another good way to do this :
另一个很好的方法是:
a.sort {|x,y| -(x <=> y)}
#2
0
You can do this:
你可以这样做:
[ 0,9,6,12,1].sort_by do |sort|
-sort
end