Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparison of Date with nil failed - ruby

Tags:

ruby

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?

like image 213
user1308317 Avatar asked Apr 03 '12 16:04

user1308317


3 Answers

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.

like image 72
ipd Avatar answered Sep 30 '22 16:09

ipd


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)

like image 31
Yo Ludke Avatar answered Sep 30 '22 18:09

Yo Ludke


I like doing them this way: valid_from && valid_from > Date.today

like image 40
Marcin Doliwa Avatar answered Sep 30 '22 18:09

Marcin Doliwa