rubocop / rubocop/ruby-style-guide

Spooky variable declaration

Open
#358 8 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Approved New Rule
Dominant language
No language data
Stars
16.5k
Forks
3.3k
PR merge metrics
No merged PRs in 30d

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

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the linked Stack Overflow discussion and reviewing the style guide's existing guidance on variable declarations. Done means the guide has an agreed recommendation for variables first introduced inside conditionals, with the examples updated to make the intended behavior clear.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.