I am running a code like this:
if valid_from > Date.today
and when I run this, I get an error saying
comparison of Date with nil failed
I assume it is happening because in some cases valid_from
is nil
. Is there a way to avoid getting this error?
You could do:
if valid_from and valid_from > Date.today
...
end
Which will short-circuit on the first clause because valid_from is nil and thus false.
Another option would be to convert both to integer
if valid_from.to_i > Date.today.to_i
(nil converts to 0 and is never bigger than the current date)
The advantage is that it is shorter and doesn't need an treatment for the extra case. Disadvantage: fails in the epoch start second (may be neglectable for a lot of scenarios)
I like doing them this way: valid_from && valid_from > Date.today
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