Skip to content

Instantly share code, notes, and snippets.

@amster
Created December 21, 2012 18:49
Show Gist options
  • Save amster/4354906 to your computer and use it in GitHub Desktop.
Save amster/4354906 to your computer and use it in GitHub Desktop.
Ruby local scoping: when exceptions happen or not.
def a
# Should error because it's not assigned in the current scope.
puts foobar
end
def b
# This code path isn't run but it's still in the same scope.
if false
foobar = 123
end
# Should print nil
puts foobar
end
def c
# Looky, new scope!
proc do
foobar = 123
end
# Should error
puts foobar
end
begin; a; rescue Exception => e; puts "ERROR: #{e.message}"; end # Should error
begin; b; rescue Exception => e; puts "ERROR: #{e.message}"; end # => nil
begin; c; rescue Exception => e; puts "ERROR: #{e.message}"; end # Should error
# Interesting related links:
# http://stackoverflow.com/questions/4154864/i-dont-understand-ruby-local-scope
# http://stackoverflow.com/questions/4021477/in-ruby-why-after-starting-irb-foo-nil-says-undefined-error-and-foo-nil-gi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment