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

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

    You can do this without overriding the spaceship operator by defining a new comparison method.

    class Child
      include Comparable   
      def compare_by_category(other)
        return 0 if !category && !other.category
        return 1 if !category
        return -1 if !other.category
        category.position <=> other.category.position
      end
    end
    

    The sort method can take a block, so you can then sort using this new method:

    children.sort {|a,b| a.compare_by_category(b) }
    

提交回复
热议问题