我已經檢測到一個變量聲明的意外行爲爲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
塊情況。