Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

@games = @teams.reduce([]) { |memo, team| memo + team.games }.sort_by(&:game_date)

Any good way of doing this?

like image 354
Kamilski81 Avatar asked Jan 05 '12 05:01

Kamilski81


2 Answers

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
like image 126
UncleGene Avatar answered Oct 01 '22 17:10

UncleGene


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.

like image 21
mu is too short Avatar answered Oct 01 '22 18:10

mu is too short