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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With