user1308317
user1308317

Reputation: 87

comparison of Date with nil failed - 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?

Upvotes: 6

Views: 9691

Answers (3)

Marcin Doliwa
Marcin Doliwa

Reputation: 3659

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

Upvotes: 2

Yo Ludke
Yo Ludke

Reputation: 2269

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)

Upvotes: 5

ipd
ipd

Reputation: 5714

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.

Upvotes: 9

Related Questions