排序:基于Ruby的多个条件排序数组

编程入门 行业动态 更新时间:2024-10-17 21:19:46
本文介绍了排序:基于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的多个条件排序数组

本文发布于:2023-11-30 09:27:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649499.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   数组   条件   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!