排序:基于Ruby的多个条件排序数组 [英] Sorting: Sort array based on multiple conditions in Ruby

查看:130
本文介绍了排序:基于Ruby的多个条件排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mulitdimensional阵列像这样:

I have a mulitdimensional array like so:

[
  [name, age, date, gender]
  [name, age, date, gender]
  [..]
]

我不知道排序取决于多个条件这阵......比如最好的方式,我将如何排序的基础上的年龄 第一个的然后叫什么名字?

I'm wondering the best way to sort this array based on multiple conditions...For instance, how would I sort based on age first then by name?

我是用像这样的排序方法瞎搞:

I was messing around with the sort method like so:

array.sort { |a,b| [ a[1], a[0] ] <=> [ b[1], b[0] ] }

另外,我真的不明白这个语法,我没有得到我期望的结果。我应该使用排序的方法?我应该通过映射单独比较结果数组?

Besides that I don't really understand this syntax, I'm not getting the results I would expect. Should I be using the sort method? Should I be individually comparing results by mapping the array?

推荐答案

您应该的总是的使用 sort_by 的键控排序。它不仅是更具可读性,这也是的的更有效。此外,我还要preFER使用解构绑定,再一次,为便于阅读:

You should always use sort_by for a keyed sort. Not only is it much more readable, it is also much more efficient. In addition, I would also prefer to use destructuring bind, again, for readability:

ary.sort_by {|name, age| [age, name] }

这篇关于排序:基于Ruby的多个条件排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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