Can someone please check me on this behavior I’m noticing?
If you don’t assign anything to a local variable and try to print it out it generates an exception as expected. If you assign the local variable in an unreachable code path, it works. Should this be the case?
def a
# Should generate an error because foobar is not defined.
puts foobar
end
def b
# This block never is run but foobar is entered into the symbol table.
if false
foobar = 123
end
# This succeeds in printing nil
puts foobar
end
begin; a; rescue Exception => e; puts "ERROR: #{e.message}"; end
begin; b; rescue Exception => e; puts "ERROR: #{e.message}"; end
Yes, this is correct. Ruby scopes variables during parsing, not during the function’s runtime. So, simply referencing a variable is enough to define it, even if it is referenced in a code path that is unreachable.
I ran into this a while back – see this blog post for a writeup of the behavior.