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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Thanks, I also just found another StackOverflow question: stackoverflow.com/questions/4154864/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.