Bug #10996
closedInline if statements should hoist variables.
Description
A multiline if statement hoists local variables to the parent scope. An inline if statement does not.
We can see that in this first example, the a
declared in the conditional is available both in the body and in the parent, after the if-statement is executed.
if a = 'A'
a # => "A"
end
a # => "A"
However, when refactoring to an inline-if-statement, the variable is no longer available.
a if a = 'A' # ~> NameError: undefined local variable or method `a' for main:Object
# ~> NameError
# ~> undefined local variable or method `a' for main:Object
# ~>
# ~> /var/folders/7g/mbft22555w3_2nqs_h1kbglw0000gn/T/seeing_is_believing_temp_dir20150323-47886-ay5rau/program.rb:1:in `<main>'
Inline if statements should hoist variables, too. For both consistency and convenience.
Updated by matz (Yukihiro Matsumoto) about 9 years ago
- Status changed from Open to Rejected
The fundamental rule is that local variables are defined by the first assignment. For consistency, I will not bend this rule for if modifiers.
Matz.
Updated by josh.cheek (Josh Cheek) over 8 years ago
Yukihiro Matsumoto wrote:
The fundamental rule is that local variables are defined by the first assignment. For consistency, I will not bend this rule for if modifiers.
Matz.
That's why it seems like this should be turned on, since it is assigned first. eg the if-statement body would work if it were dynamically accessed.
eval 'a' if a = 'A' # => "A"
binding.local_variable_get 'b' if b = 'B' # => "B"