Why is a variable declared when it appears in "if false"?

I find it hard to understand how the next variable is set to nil , although it seems like it is not assigned anywhere.

I tried this in ruby 2.1.2 and in ruby 1.8.7 . Both give the same results.

How does this happen?

 irb(main):002:0> foo NameError: undefined local variable or method `foo' for main:Object irb(main):003:0> if false irb(main):004:1> foo = 1 irb(main):005:1> end irb(main):006:0> foo => nil 
0
variables ruby
source share
1 answer

Ruby processes jobs at the analyzer level. From the doc:

A local variable is created when the parser encounters an assignment, and not when assigned:

 a = 0 if false # does not assign to a p local_variables # prints [:a] pa # prints nil 
0
source share

All Articles