Abd00s Abd00s - 2 years ago 89
Ruby Question

Why is the .try method terminating my program?

I am capturing a string date from params that should be in the form of YYYY-DD-MM. If the parameter is an invalid date, I want

to be assigned to
. Like if the param was 2013-40-50 for example. I am able to do so successfully with :

minimum = Date.try(:parse, (params[:newer_than])) if params[:newer_than].present?

If the date is of the correct format, it is assigned to
, otherwise
is. However, in the case where it is
, the program terminates and I get ArgumentError - invalid date.

The whole idea of me using
is that if it in fact fails, it's okay, move along. I am handling the case if it were nil afterward. The error is thrown on the line assigning to

How can achieve that?

Answer Source

You can use rescue for your goal:

minimum = begin
rescue ArgumentError, TypeError

According to docs, try just like the regular Ruby Object#send if methos defined on object, so it does not prevent errors like ArgumentError and TypeError.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download