Andrew Arrow Andrew Arrow - 5 months ago 15
Ruby Question

is it best practice to define vars first before using them inside a begin block?

foo = ''
begin
foo = 'hi there'
rescue
end
puts foo


if I don't delcare foo = '' at the top before the begin it still works. But I see a lot of people do this. And it feels better. But is it best practice?

Answer

This is part paranoia, and part clarity. In this trivial example there's unlikely to be an issue, but what if you had this?

begin
  foo = complicated_method_call(with: lots_of_arguments, and: another_call(with: args))
rescue
end

A whole bunch of stuff could go wrong there, and if that's the case you end up with foo being nil.

Now, using a blind rescue is generally bad form, you ideally want to scope down to just the ones your code might trigger.

Remember Ruby variables are defined at the method level, any instance of them in the method makes them defined, but they will have a default of nil which can be undesirable.

Comments