我搜索了一个无济于事的答案,有一个类似的问题,但答案在这种情况下不起作用,它按数字项排序。相似的问题-没用,我正在尝试使用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]}
Run Code Online (Sandbox Code Playgroud)
任何指导肯定会有所帮助。
样本数据:
这是一种简单的方法:
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"] ]
Run Code Online (Sandbox Code Playgroud)
对于多个字段,首先按降序排序,然后依次按升序对其他每个字段排序:
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"]]
Run Code Online (Sandbox Code Playgroud)
<=>创建一个自定义类来反转(包括)的结果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],
]}
Run Code Online (Sandbox Code Playgroud)
输出:
{: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"}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果您想要降序排序的对象是数值,您可以简单地使用一元运算符-:
people.sort_by {|person| [-person.age, person.name] }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1305 次 |
| 最近记录: |