Ruby: Are the variables defined in the If / else statement accessible outside the if / else?

def foo #bar = nil if true bar = 1 else bar = 2 end bar #<-- shouldn't this refer to nil since the bar from the if statement is removed from the stack? end puts foo # prints "1" 

I always thought that you need to create a temporary variable and define it as nil or the initial value so that the variables defined inside the if / else statement are saved outside the scope of the if / else and not disappear from the stack ?? Why does it print 1 and not zero?

+7
ruby
source share
1 answer

Variables are local to a function, class or module, a proc , block.

There is an expression in ruby ​​if, and branches do not have their own volume.

Also note that whenever the parser sees the purpose of a variable, it will create a variable in the scope even if this code path is not executed :

 def test if false a = 1 end puts a end test # ok, it nil. 

It is similar to JavaScript, although it does not raise the variable to the top of the field:

 def test puts a a = 1 end test # NameError: undefined local variable or method `a' for ... 

So, even if what you said was true, it still would not be nil .

+16
source share

All Articles