Comparison of Date with nil failed - ruby
I am running code like this:
if valid_from > Date.today
and when i run this i get the error
date comparison with nil failed
I assume this is happening because in some cases valid_from
there is nil
. Is there a way to avoid this error?
You can do:
if valid_from and valid_from > Date.today
...
end
That there will be a short circuit in the first clause, because valid_from is nil and therefore false.
Another option is to convert both to integer
if valid_from.to_i > Date.today.to_i
(nil converts to 0 and never exceeds the current date)
The advantage is that it is shorter and does not need treatment for an additional case. Disadvantage: Failure at the beginning of the second stage (may be negligible for a large number of scenarios)
I like to do it this way: valid_from && valid_from > Date.today