我已经检测到一个变量声明的意外行为为if
块了解局部变量的作用域:红宝石,在if块
puts "local_variables: #{local_variables}"
puts "defined? my_variable ini: #{defined? my_variable}"
if true
my_variable = 1
puts "local_variables in the 'if' block: #{local_variables}"
end
1.times do
my_variable_2 = 1
puts "local_variables in the 'times' block: #{local_variables}"
puts "defined? my_variable_2 in the 'times' block: #{defined? my_variable_2}"
end
puts "defined? my_variable_2 end: #{defined? my_variable_2}"
puts "defined? my_variable end: #{defined? my_variable}"
puts "my_variable: #{my_variable}"
结果是:
local_variables: [:my_variable]
defined? my_variable ini:
local_variables in the 'if' block: [:my_variable]
local_variables in the 'times' block: [:my_variable_2, :my_variable]
defined? my_variable_2 in the 'times' block: local-variable
defined? my_variable_2 end:
defined? my_variable end: local-variable
my_variable: 1
问题:
- 声明为
if
块的变量变得可以从之外访问块,这是正确的吗?为什么它对我来说看起来反直觉? - 为什么
times
块的行为与if
块不同?
我一直在阅读this documentation,但我没有看到if
块情况。