How and when are Ruby instances created

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 does the kol variable get an instance on nil , although the condition (1 == 2) fails?

+7
source share
1 answer

This is due to the way the Ruby interpreter reads the code.

Assigning a variable does not have to be done; the Ruby interpreter just needs to see that the variable exists on the left side of the job. (Programming Ruby 1.9 and 2.0)

 a = "never used" if false [99].each do |i| a = i # this sets the variable in the outer scope end a # => 99 

"The Ruby interpreter creates the variable even if the assignment is not actually executed." http://www.jacopretorius.net/2012/01/block-variable-scope-in-ruby.html

+7
source

All Articles