7

from 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 

my question is, why the does variable kol get instantiated to nil even though the condition (1==2) fails?

4

1 回答 1

7

It has to do with the way the Ruby interpreter reads the code.

The assignment to the variable doesn't have to be executed; the Ruby interpreter just needs to have seen that the variable exists on the left side of an assignment. (Programming 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

"Ruby interpreter creates the variable even though the assignment isn't actually executed." http://www.jacopretorius.net/2012/01/block-variable-scope-in-ruby.html

于 2013-03-30T19:18:43.083 回答