So I've built a custom array of users like such:
所以我构建了一个自定义的用户数组,如:
[["user1",432],["user1",53],["user9",58],["user5",75],["user3",62]]
I want to sort them by the 2n'd value in each array, from largest to smallest. I have a feeling using sort or sort_by for arrays is the way to do this, but I'm not really sure how to accomplish it
我想按每个数组中的2n'd值对它们进行排序,从最大到最小。我有一种感觉,使用sort或sort_by进行数组是这样做的方法,但我不确定如何实现它
3 个解决方案
#1
40
sort_by
If you're interested in sort_by
, you could destructure your inner arrays
如果您对sort_by感兴趣,可以对内部数组进行解构
array.sort_by { |_, x| x }.reverse
or call the index operator
或者调用索引运算符
array.sort_by { |x| x[1] }.reverse
Instead of reversing you could negate values returned from the block.
而不是反转你可以否定从块返回的值。
array.sort_by { |_, x| -x }
array.sort_by { |x| -x[1] }
Yet another alternative would be to use an ampersand and Array#last
.
另一个替代方案是使用&符号和数组#last。
array.sort_by(&:last).reverse
sort
A solution using sort
could be
使用sort的解决方案可能是
array.sort { |x, y| y[1] <=> x[1] }
#2
2
use this: array.sort_by { |a| -a[1] }
使用它:array.sort_by {| a | -a [1]}
#3
0
One more solution to sort_by
in reverse (-
doesn't work in all cases, think sorting by string):
反向排序的另一个解决方案( - 在所有情况下都不起作用,考虑按字符串排序):
class Invertible
include Comparable
attr_reader :x
def initialize(x)
@x = x
end
def <=> (x)
x.x <=> @x
end
end
class Object
def invertible
Invertible.new(self)
end
end
[1, 2, 3].sort_by(&:invertible) #=> [3, 2, 1]
["a", "b", "c"].sort_by(&:invertible) #=> ["c", "b", "a"]
It is slower than reverse in simple case, but may work better with complex sorts:
在简单的情况下,它比反向慢,但对于复杂的排序可能会更好:
objs.sort_by do |obj|
[obj.name, obj.date.invertible, obj.score, ...]
end
#1
40
sort_by
If you're interested in sort_by
, you could destructure your inner arrays
如果您对sort_by感兴趣,可以对内部数组进行解构
array.sort_by { |_, x| x }.reverse
or call the index operator
或者调用索引运算符
array.sort_by { |x| x[1] }.reverse
Instead of reversing you could negate values returned from the block.
而不是反转你可以否定从块返回的值。
array.sort_by { |_, x| -x }
array.sort_by { |x| -x[1] }
Yet another alternative would be to use an ampersand and Array#last
.
另一个替代方案是使用&符号和数组#last。
array.sort_by(&:last).reverse
sort
A solution using sort
could be
使用sort的解决方案可能是
array.sort { |x, y| y[1] <=> x[1] }
#2
2
use this: array.sort_by { |a| -a[1] }
使用它:array.sort_by {| a | -a [1]}
#3
0
One more solution to sort_by
in reverse (-
doesn't work in all cases, think sorting by string):
反向排序的另一个解决方案( - 在所有情况下都不起作用,考虑按字符串排序):
class Invertible
include Comparable
attr_reader :x
def initialize(x)
@x = x
end
def <=> (x)
x.x <=> @x
end
end
class Object
def invertible
Invertible.new(self)
end
end
[1, 2, 3].sort_by(&:invertible) #=> [3, 2, 1]
["a", "b", "c"].sort_by(&:invertible) #=> ["c", "b", "a"]
It is slower than reverse in simple case, but may work better with complex sorts:
在简单的情况下,它比反向慢,但对于复杂的排序可能会更好:
objs.sort_by do |obj|
[obj.name, obj.date.invertible, obj.score, ...]
end