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"
Run Code Online (Sandbox Code Playgroud)
我一直认为你必须创建一个临时变量并将其定义为nil或初始值,以便在if/else语句中定义的变量将保持在if/else语句的范围之外而不会从堆栈中消失?为什么打印1而不是零?
Kar*_*ath 50
变量是函数,类或模块定义的局部变量,a proc,块.
在ruby中if是一个表达式,并且分支没有自己的范围.
另请注意,只要解析器看到变量赋值,它就会在作用域中创建一个变量,即使该代码路径未执行:
def test
if false
a = 1
end
puts a
end
test
# ok, it's nil.
Run Code Online (Sandbox Code Playgroud)
它有点类似于JavaScript,虽然它没有将变量提升到范围的顶部:
def test
puts a
a = 1
end
test
# NameError: undefined local variable or method `a' for ...
Run Code Online (Sandbox Code Playgroud)
所以即使你说的是真的,它仍然不会nil.
| 归档时间: |
|
| 查看次数: |
6043 次 |
| 最近记录: |