在 ruby​​ 中使用 sort_by(用于导轨)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9148174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:46:15  来源:igfitidea点击:

using sort_by in ruby (for rails)?

ruby-on-railsrubyruby-on-rails-3

提问by Elliot

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

我想按每个数组中的第 2 个值对它们进行排序,从最大到最小。我有一种感觉对数组使用 sort 或 sort_by 是这样做的方法,但我不确定如何完成它

回答by Jan

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 ampersandand Array#last.

另一种替代方案是使用一种符号Array#last

array.sort_by(&:last).reverse

sort

种类

A solution using sortcould be

使用的解决方案sort可能是

array.sort { |x, y| y[1] <=> x[1] }

回答by Vasiliy Ermolovich

use this: array.sort_by { |a| -a[1] }

用这个: array.sort_by { |a| -a[1] }

回答by Victor Moroz

One more solution to sort_byin reverse (-doesn't work in all cases, think sorting by string):

另一种sort_by反向解决方案(-不适用于所有情况,请考虑按字符串排序):

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:

在简单的情况下它比 reverse 慢,但在复杂的排序中可能会更好:

objs.sort_by do |obj|  
  [obj.name, obj.date.invertible, obj.score, ...]
end