我一直没有找到答案,有一个类似的问题,但是在这种情况下答案不起作用,它是根据数字项排序的。 Similar Question -That did not work我正在尝试使用ruby的sort_by对降序排列的项进行排序,而另一项则按升序进行排序。我所能找到的只是其中一个。
这是代码:
# Primary sort Last Name Descending, with ties broken by sorting Area of interest.
people = people.sort_by { |a| [ a.last_name, a.area_interest]}
任何指导肯定会有所帮助。
样本数据:
输入
输出
最佳答案
制作一个自定义类,以反转<=>
(包括 Comparable
)的结果。
用自定义类包装要排序的对象。
例子:
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],
]}
输出:
{: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"}
顺便说一句,如果要排序的对象是数字值,则可以简单地使用一元运算符
-
:people.sort_by {|person| [-person.age, person.name] }