3

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
Amy
  • 1,318
  • 3
  • 12
  • 24

1 Answers1

6

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.

Chris Heald
  • 61,439
  • 10
  • 123
  • 137
  • 1
    In Ruby terms, each symbol like `foobar` can be either a method or a variable, but is presumed to be a method unless it's referenced as a variable. In this case, it's "defined" to be a variable, but the variable is not defined with any particular value. – tadman Dec 21 '12 at 18:34
  • Thanks, I also just found another StackOverflow question: http://stackoverflow.com/questions/4154864/i-dont-understand-ruby-local-scope – Amy Dec 21 '12 at 18:43