我有一个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的多个条件排序数组
发布评论