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

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

    To be fair, I'm not very familiar with Ruby, so take this as more of an algorithm idea rather than a code one... and rewrite the ?: operator as whatever Ruby has that's cleaner.

    Can't you just check for nil in the comparison:

    class Parent
      def sorted_children
         children.sort{|a,b|( a and b ) ? a <=> b : ( a ? -1 : 1 ) }
      end
    end
    

    Edited to use Glenra's code, which implements the same thing as mine but in a smaller (and probably easier to read) amount of code.

提交回复
热议问题