Matthew Lindfield Seager

Matthew Lindfield Seager

Ruby Pop Quiz

if false
  foo = 'bar'


What will the result be?

a. foo
b. ‘bar’
c. NameError (undefined local variable or method `foo’ for main:Object)
d. ‘foo’
e. nil
f. None of the above

With my (admittedly limited) understanding of Ruby it was my intuition that the foo = 'bar' line would not get evaluated at all and therefore this would result in a NameError (option C).

I was surprised to learn that the result was actually nil. That is, the program knows foo exists but nothing is assigned to it.

With this new piece of information my intuition is now that the line is parsed but not evaluated (executed?). I’m guessing the process of parsing adds a foo node to the Abstract Syntax Tree (AST) and the presence of foo in the AST prevents the NameError I previously expected.

Now I need to figure out how to confirm that hunch… and whether it’s a good use of my time to do so ¯_(ツ)_/¯