Ruby变量如何以及何时实例化

Rai*_*DFW 7 ruby ruby-on-rails

来自rails console:

development environment (Rails 3.2.9)
1.9.2p320 :001 > defined?(kol)
 => nil 
1.9.2p320 :002 > if 1==2
1.9.2p320 :003?>   kol = 'mess'
1.9.2p320 :004?>   end
 => nil 
1.9.2p320 :005 > defined?(kol)
 => "local-variable" 
1.9.2p320 :006 > kol
 => nil 
Run Code Online (Sandbox Code Playgroud)

我的问题是,即使条件(1 == 2)失败,为什么变量kol被实例化nil

Luí*_*lho 7

它与Ruby解释器读取代码的方式有关.

不必执行对变量的赋值; Ruby解释器只需要看到变量存在于赋值的左侧.(编程Ruby 1.9和2.0)

a = "never used" if false
[99].each do |i|
  a = i # this sets the variable in the outer scope
end
a # => 99
Run Code Online (Sandbox Code Playgroud)

"Ruby解释器创建变量,即使实际上没有执行赋值." http://www.jacopretorius.net/2012/01/block-variable-scope-in​​-ruby.html