开发者

Can you sort and throw all the `nil` results in the back?

开发者 https://www.devze.com 2023-04-09 05:18 出处:网络
I wo开发者_开发百科uld like to start sorting all my results by a new field. Unfortunately, a lot of my older fields have a nil for a timestamp. How can I perform this method and put all the nils in th

I wo开发者_开发百科uld like to start sorting all my results by a new field. Unfortunately, a lot of my older fields have a nil for a timestamp. How can I perform this method and put all the nils in the back?

.sort{|a,b| b.offering_referral_timestamp <=> a.offering_referral_timestamp}

Thanks


a <=> b 
returns -1 if a < b
returns 0 if a == b
returns 1 if a > b

so I think this should work (if you want all nil at the end, they should be bigger than other elements):

.sort{|a,b| a.offering_referral_timestamp.nil? ? 1 : (b.offering_referral_timestamp.nil? ? -1 : a.offering_referral_timestamp <=> b.offering_referral_timestamp)}
0

精彩评论

暂无评论...
验证码 换一张
取 消