0

I'm finding it difficult to understand how the following variable is being set to nil, while it seems that it isn't assigned anywhere.

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

How is this happening?

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
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
Arjan
  • 6,264
  • 2
  • 26
  • 42
  • (The variable is *not* "assigned" a value, it is however introduced as a local variable - nil is merely the default value, as a variable must evaluate to *a* value.) – user2864740 Sep 11 '14 at 09:13

1 Answers1

0

Ruby handles assignments at the parser level. From the documentation:

The local variable is created when the parser encounters the assignment, not when the assignment occurs:

a = 0 if false # does not assign to a

p local_variables # prints [:a]

p a # prints nil
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • 1
    "Parser encounters the assignment" is a bit vague; consider `def x(t); return y if t; y = "hello world"; end; x(true)` which throws a NameError. Yet the parser "encountered" the entire method body before `x` was invoked. – user2864740 Sep 11 '14 at 09:20