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

前端 未结 7 740
孤城傲影
孤城傲影 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:50

    I haven't done Ruby in a while, but you could split the null-checking from the sorting (and just allow Child#position to return null):

    def sorted_children
      children.reject{|c| c.position.nil?}.sort_by(&:position) +
        children.select{|c| c.position.nil?}
    end
    

    Admittedly it's not the most efficient solution, but it doesn't have any magic numbers.

提交回复
热议问题