rubocop / rubocop/ruby-style-guide
Spooky variable declaration
Nobody has claimed this yet.
- 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
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
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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