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

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

    How about in Child defining <=> to be based on category.position if category exists, and sorting items without a category as always greater than those with a category?

    class Child
      # Not strictly necessary, but will define other comparisons based on <=>
      include Comparable   
      def <=> other
        return 0 if !category && !other.category
        return 1 if !category
        return -1 if !other.category
        category.position <=> other.category.position
      end
    end
    

    Then in Parent you can just call children.sort.

提交回复
热议问题