In ruby/rails, how do I sort on a date value where the date can sometimes be null?

前端 未结 2 1981
再見小時候
再見小時候 2020-12-20 16:59

I would like to sort my games by game_date, but sometimes the game_date may be null, and I will get an exception: undefined method `to_datetime\' for nil:NilClass

         


        
2条回答
  •  别那么骄傲
    2020-12-20 17:37

    If you just want to drop entries without date, simplest solution -

    ar.select(&:date).sort_by(&:date)
    

    adding nils at the end can be done with

    ar.select(&:date).sort_by(&:date) + ar.reject(&:date)
    

    If you happen to know the range of possible dates, you can be fine with something like

    ar.sort_by{|e| e.date || Date.new(9999)}
    

    BTW, reduce in your statement can be changed to (IMHO) more clear

    @games = @teams.map(&:games).flatten
    

提交回复
热议问题