sorting a ruby array of objects by an attribute that could be nil

前端 未结 7 621
孤城傲影
孤城傲影 2020-12-08 04:23

I have an array of objects that I need to sort by a position attribute that could be an integer or nil, and I need the objects that have the nil position to be at the end of

相关标签:
7条回答
  • 2020-12-08 04:59

    I would just tweak your sort to put nil items last. Try something like this.

    foo = [nil, -3, 100, 4, 6, nil, 4, nil, 23]
    
    foo.sort { |a,b| a && b ? a <=> b : a ? -1 : 1 }
    
    => [-3, 4, 4, 6, 23, 100, nil, nil, nil]
    

    That says: if a and b are both non-nil sort them normally but if one of them is nil, return a status that sorts that one larger.

    0 讨论(0)
提交回复
热议问题