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

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

    The most simple solution for me is

    def sorted_children(children)
      children.sort_by { |child| child.position || -1}
    end
    

提交回复
热议问题