根据某些元素中可能为零的属性对数组进行排序 [英] Sorting an array based on an attribute that may be nil in some elements

查看:19
本文介绍了根据某些元素中可能为零的属性对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组

[<#a star=1  val=1>, <#a star=nil val=3> , <#a star=2  val=2>]

我需要数组按时间排序,然后按 val

i need the array to be sorted by time, then by val

[ <#a star=2  val=2>, <#a star=1  val=1>, <#a star=nil val=3> ]

但是使用 sort_by 会抛出错误,因为时间为零.

but using the sort_by throws an error because the time is nil.

我现在正在使用一种丑陋的排序方式,但我相信有一个很好的方法来解决它

I am using an ugly way to sort right now, but i am sure there is a nice way to go about it

starred=[]
@answers.each {|a| (starred << a) if a.starred }
@answers=@answers-starred
starred=starred.sort_by {|a| a.starred }.reverse
@answers=starred+@answers

推荐答案

starred.sort_by { |a| [a ? 1 : 0, a] }

当它必须比较两个元素时,它比较一个数组.当 Ruby 比较数组时(调用 === 方法),它比较第一个元素,只有当第一个元素相等时才去比较第二个元素.<代码>?1 : 0 保证,我们将 Fixnum 作为第一个元素,所以它应该没有错误.

When it has to compare two elements, it compares an arrays. When Ruby compares arrays (calls === method), it compares 1st element, and goes to the 2nd elements only if the 1st are equal. ? 1 : 0 garantees, that we'll have Fixnum as 1st element, so it should be no error.

如果你做?0 : 1, nil 将出现在数组的末尾而不是开头.
下面是一个例子:

If you do ? 0 : 1, nil will appear at the end of array instead of begining.
Here is an example:

irb> [2, 5, 1, nil, 7, 3, nil, nil, 4, 6].sort_by { |i| [i ? 1 : 0, i] }
=> [nil, nil, nil, 1, 2, 3, 4, 5, 6, 7]

irb> [2, 5, 1, nil, 7, 3, nil, nil, 4, 6].sort_by { |i| [i ? 0 : 1, i] }
=> [1, 2, 3, 4, 5, 6, 7, nil, nil, nil]

这篇关于根据某些元素中可能为零的属性对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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