Ruby,了解 if 块中的局部变量范围

fgu*_*len 4 ruby binding scope

我在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}"
Run Code Online (Sandbox Code Playgroud)

结果是:

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}"
Run Code Online (Sandbox Code Playgroud)

问题:

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

我一直在阅读这个文档,但我没有看到if块案例。

eik*_*iko 5

在 ruby​​ 中,类、模块、函数、块和过程都有自己的作用域,因此在它们内部定义的局部变量通常无法在它们之外访问。

在 ruby​​ 中,诸如ifwhilefor 之类的逻辑语句没有自己的作用域,因此其中定义的变量会保留在使用它们的类、模块、功能块或 proc 中。

这是一种设计选择,也是 ruby​​ ruby​​ 的一部分!这可能会让人觉得违反直觉,因为像 c 这样的语言对if语句有单独的作用域,而一些(但不是全部)解释型语言模仿了这一点。