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

前端 未结 2 1975
再見小時候
再見小時候 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
    
    0 讨论(0)
  • 2020-12-20 17:39

    An easy way would be to split your array into those with nils and those without, then sort the non-nil half as desired and paste them together:

    parts  = a.partition { |o| o.date.nil? }
    sorted = parts.last.sort_by(&:date) + parts.first
    

    This approach will work with any method (i.e. not just with date) and it should be quick enough.

    0 讨论(0)
提交回复
热议问题