Abd00s Abd00s - 7 months ago 19
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

nil
to be assigned to
minimum
. 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
minimum
, otherwise
nil
is. However, in the case where it is
nil
, the program terminates and I get ArgumentError - invalid date.

The whole idea of me using
.try
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
minimum
.

How can achieve that?

Answer

You can use rescue for your goal:

minimum = begin
  Date.parse(params[:newer_than])
rescue ArgumentError, TypeError
  nil
end

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.