ruby – 使用tiebreaker按长度排序数组

前端之家收集整理的这篇文章主要介绍了ruby – 使用tiebreaker按长度排序数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个阵列数组,我想按最长到最短排序.我用sort_by很容易实现这一点
> a =  [ [1,2,9],[4,5,6,7],[1,3] ]
> a.sort_by(&:length).reverse # or a.sort_by {|e| e.length}.reverse
=> [[4,3],9]]

然而,我想要的是对于相等长度的列表有一种打破平局.如果两个列表的长度相等,则应该首先列出最后一个条目的列表.所以在上面,应该切换[1,9]和[1,3].

我不关心两个列表具有相等长度和相等的最后一个元素的情况,如果发生这种情况,它们可以是任何顺序.我不知道是否/如何使用ruby内置排序来实现这一点.

解决方法

您仍然可以使用 sort_by执行此操作,您只需要了解 Ruby arrays compare element-by-element

ary <=> other_ary → -1,+1 or nil

[…]

Each object in each array is compared (using the <=> operator).

Arrays are compared in an “element-wise” manner; the first two elements that are not equal will determine the return value for the whole comparison.

这意味着你可以使用数组作为sort_by键,然后输入一些整数否定来反转排序顺序,你得到:

a.sort_by { |e| [-e.length,-e.last] }

这将为您提供您正在寻找的[[4,3]].

如果你没有使用数字,那么“否定反转命令”技巧将不起作用,那么使用Shaunak’s sort方法.

原文链接:https://www.f2er.com/ruby/267530.html

猜你在找的Ruby相关文章