如何按多个条件以不同的顺序排序? [英] How can I sort by multiple conditions with different orders?

查看:94
本文介绍了如何按多个条件以不同的顺序排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很想在没有猴子补丁的情况下进行处理,但是我还找不到其他选择.

I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.

我有一个需要在多个条件下排序的数组(在Ruby中).我知道如何使用sort方法,并且使用了技​​巧,可以使用多个选项对多个条件进行排序.但是,在这种情况下,我需要第一个条件对升序进行排序,第二个条件对降序进行排序.例如:

I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example:

ordered_list = [[1, 2], [1, 1], [2, 1]]

有什么建议吗?

刚意识到我应该提到我不能轻易比较第一个和第二个值(我实际上在这里使用对象属性).因此,对于一个简单的示例,它更像是:

Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like:

ordered_list = [[1, "b"], [1, "a"], [2, "a"]]

推荐答案

怎么样:



ordered_list = [[1, "b"], [1, "a"], [2, "a"]]
ordered_list.sort! do |a,b|
  [a[0],b[1]] <=> [b[0], a[1]]
end

这篇关于如何按多个条件以不同的顺序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆