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
1
  • (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.) Commented Sep 11, 2014 at 9:13

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

"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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.