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?

1
  • irb works differently in regards to local variables than the interpreter -- beware. Commented Mar 30, 2013 at 19:40

1 Answer 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.