首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sort_by红宝石,一个下降,一个上升

Sort_by红宝石,一个下降,一个上升
EN

Stack Overflow用户
提问于 2014-03-01 19:20:04
回答 2查看 1.5K关注 0票数 5

我已经在这个问题上寻找了一个答案,但没有结果,有一个类似的问题,但在这种情况下答案无效,它对一个数字项进行排序。Similar Question -That did not work,我正在尝试使用ruby的sort_by来排序一个项目下降和另一个升序。我只能找到一个或另一个。

以下是代码:

代码语言:javascript
复制
# Primary sort Last Name Descending, with ties broken by sorting Area of interest.
people = people.sort_by { |a| [ a.last_name, a.area_interest]}

任何指导都肯定会有所帮助。

样本数据:

输入

  • 罗素,逻辑
  • 欧拉图论
  • Galois,抽象代数
  • 高斯数论
  • 图灵算法
  • 伽罗瓦逻辑

输出

  • 图灵算法
  • 罗素,逻辑
  • 高斯数论
  • Galois,抽象代数
  • 伽罗瓦逻辑
  • 欧拉图论
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-01 19:38:28

创建一个自定义类,反转<=>的结果(包括Comparable)。

用自定义类包装要降序排序的对象。

示例:

代码语言:javascript
复制
class Descending
  include Comparable
  attr :obj

  def initialize(obj)
    @obj = obj
  end
  def <=>(other)
    return -(self.obj <=> other.obj)
  end
end

people = [
  {last_name: 'Russell', area_interest: 'Logic'},
  {last_name: 'Euler', area_interest: 'Graph Theory'},
  {last_name: 'Galois', area_interest: 'Abstract Algebra'},
  {last_name: 'Gauss', area_interest: 'Number Theory'},
  {last_name: 'Turing', area_interest: 'Algorithms'},
  {last_name: 'Galois', area_interest: 'Logic'},
]
puts people.sort_by {|person| [
  Descending.new(person[:last_name]),  # <---------
  person[:area_interest],
]}

产出:

代码语言:javascript
复制
{:last_name=>"Turing", :area_interest=>"Algorithms"}
{:last_name=>"Russell", :area_interest=>"Logic"}
{:last_name=>"Gauss", :area_interest=>"Number Theory"}
{:last_name=>"Galois", :area_interest=>"Abstract Algebra"}
{:last_name=>"Galois", :area_interest=>"Logic"}
{:last_name=>"Euler", :area_interest=>"Graph Theory"}

顺便说一句,如果您希望排序降序的对象是一个数值,您可以简单地使用一元运算符-

代码语言:javascript
复制
people.sort_by {|person| [-person.age, person.name] }
票数 4
EN

Stack Overflow用户

发布于 2014-03-02 06:22:49

这是一个直截了当的方法:

代码语言:javascript
复制
a = [ ['Russell', 'Logic'],           ['Euler', 'Graph Theory'],
      ['Galois', 'Abstract Algebra'], ['Gauss', 'Number Theory'],
      ['Turing', 'Algorithms'],       ['Galois', 'Logic'] ]

a.sort { |(name1,field1),(name2,field2)|
  (name1 == name2) ? field1 <=> field2 : name2 <=> name1 }
#=> [ ["Turing", "Algorithms"],   ["Russell", "Logic"],
#     ["Gauss", "Number Theory"], ["Galois", "Abstract Algebra"],
#     ["Galois", "Logic"],        ["Euler", "Graph Theory"] ]

对于多个字段,先按降序排序,然后依次对其他字段按升序排序:

代码语言:javascript
复制
a = [ %w{a b c}, %w{b a d}, %w{a b d}, %w{b c a}, %w{a b c}, %w{b c b}]
  #=> [["a", "b", "c"], ["b", "a", "d"], ["a", "b", "d"],
  #    ["b", "c", "a"], ["a", "b", "c"], ["b", "c", "b"]] 

a.sort { |e,f| e.first == f.first ? e[1..-1] <=> f[1..-1] : f <=> e }
  #=> [["b", "a", "d"], ["b", "c", "a"], ["b", "c", "b"],
  #    ["a", "b", "c"], ["a", "b", "c"], ["a", "b", "d"]] 
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22119121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档