Andrew Arrow Andrew Arrow - 1 year ago 87
Ruby Question

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

foo = ''
foo = 'hi there'
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 Source

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

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

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.

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