在 ruby/rails 中,如何对日期有时为空的日期值进行排序? [英] In ruby/rails, how do I sort on a date value where the date can sometimes be null?
本文介绍了在 ruby/rails 中,如何对日期有时为空的日期值进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按 game_date 对我的游戏进行排序,但有时 game_date 可能为 null,并且我会得到一个异常: undefined method `to_datetime' for nil:NilClass
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)
有什么好的方法吗?
推荐答案
如果你只想删除没有日期的条目,最简单的解决方案 -
If you just want to drop entries without date, simplest solution -
ar.select(&:date).sort_by(&:date)
在最后添加 nils 可以用
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)}
顺便说一句,reduce in your statement可以改成(恕我直言)更清楚
BTW, reduce in your statement can be changed to (IMHO) more clear
@games = @teams.map(&:games).flatten
这篇关于在 ruby/rails 中,如何对日期有时为空的日期值进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文