Can you sort and throw all the `nil` results in the back?
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)}
精彩评论