Created
December 21, 2012 18:49
-
-
Save amster/4354906 to your computer and use it in GitHub Desktop.
Ruby local scoping: when exceptions happen or not.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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