-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Open
Description
Weird things can happen when you declare a variable within a conditional that you intend to use outside of it. Example:
if false
x = 1
end
puts x # nil, even though the code declaring it was never executed
puts y # crash
I propose variables should never be declared for the first time within a conditional if you intend to use them outside.
Bad (works, but looks so scary):
if false
x = 1
end
puts x # nil
Bad (works, but if you made a mistake in your logic you get the previous scenario, so it still looks alarming / requires too much inspection to figure out why it won't blow up):
if false
x = 1
else
x = nil
end
puts x # nil
Good (self-evidently safe in a way that doesn't rely on weird parser quirk):
x = nil # Declare the default value for the variable outside the conditional
if false
x = 1
end
puts x # nil
mikegee