Skip to content

Spooky variable declaration #358

@danmichaelson

Description

@danmichaelson

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

See http://stackoverflow.com/questions/12928050/why-does-ruby-seem-to-hoist-variable-declarations-from-inside-a-case-statement-e .

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions