3

Recently I found out that a non-evaluated line, in Ruby, still assigns nil to the variable.

2.3.4 (main):0 > defined? this_never_seen_variable_before
=> nil
2.3.4 (main):0 > this_never_seen_variable_before = "value" if false
=> nil
2.3.4 (main):0 > defined? this_never_seen_variable_before
=> "local-variable"
2.3.4 (main):0 >
2.3.4 (main):0 > this_never_seen_variable_before_2
   NameError: undefined local variable or method `this_never_seen_variable_before_2' for main:Object
from (pry):119:in `<main>'
2.3.4 (main):0 > this_never_seen_variable_before_2 = "value" if false
=> nil
2.3.4 (main):0 > this_never_seen_variable_before_2
=> nil
2.3.4 (main):0 >

Would anyone have more information about it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bruno Velasco
  • 135
  • 1
  • 6

1 Answers1

2

Before your Ruby code can be run, it must first be parsed, and it's at this stage that the behavior you're experiencing originates.

As the parser scans through the code, whenever it encounters a declaration (foo = 'something') it allocates space for that variable by setting its value to nil. Whether that variable declaration is actually executed in the context of your code is irrelevant. For example:

if false
  foo = 42
end

p foo
#=> nil

In the above code's logic foo is never declared, however it's space in memory is recognized and allocated for by Ruby when the code is parsed out.

Hope this helps!

Zoran
  • 4,196
  • 2
  • 22
  • 33