2017-02-09 76 views
2

我已经检测到一个变量声明的意外行为为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 

问题:

  1. 声明为if块的变量变得可以从之外访问块,这是正确的吗?为什么它对我来说看起来反直觉?
  2. 为什么times块的行为与if块不同?

我一直在阅读this documentation,但我没有看到if块情况。

回答

4

在Ruby中,类,模块,功能模块和特效都有自己的职责范围内为其定义这样的局部变量通常不会成为他们的外部访问。

在Ruby中,逻辑语句,如如果没有自己的范围,所以在他们定义的变量坚持类,模块,功能块,或PROC他们在哪里用过的。

这是一个设计选择的是什么使Ruby红宝石的一部分!它可能会觉得反直觉的,因为像C语言有如果语句和一些(但不是全部)独立的范围解释的语言模仿。

2
  1. 是,if不会引入新的范围,所以变量可以外
  2. times使用需要的块,和块引入了一个新的范围。

要了解更多有关范围门请参阅this answer