Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`var = something rescue nil` behaviour

In Ruby you can write a rescue at the end of an assignment to catch any errors that might come up. I have a function (below: a_function_that_may_fail) where it's convenient to let it throw an error if certain conditions aren't met. The following code works well

post = {}
# Other Hash stuff
post['Caption'] = a_function_that_may_fail rescue nil

However I'd like to have post['Caption'] not even set if the function fails.

I know I can do:

begin
  post['Caption'] = a_function_that_may_fail
rescue
end

but that feels a little excessive - is there a simpler solution?

like image 844
JP. Avatar asked Apr 12 '10 11:04

JP.


1 Answers

The problem is precedence. The simplest solution:

(post['Caption'] = a_function_that_may_fail) rescue nil

Changing the precedence like this is a little esoteric, though. It would probably be better if you can rewrite your a_function_that_may_fail to return nil if it fails.

You could also use a temporary variable and test for nilness:

caption = a_function_that_may_fail rescue nil
post['Caption'] = caption unless caption.nil?

A really minor difference is that this does not set post['Caption'] if a_function_that_may_fail did not raise an exception but returned nil.

like image 197
molf Avatar answered Sep 28 '22 14:09

molf