Last active
December 26, 2015 06:19
-
-
Save travisdahlke/7107244 to your computer and use it in GitHub Desktop.
Ruby variable scoping can be tricky sometimes. Ruby will initialize the local variable 'foo' even though that line is never executed. Since it's now in the local scope, the method 'foo' doesn't get run during the second if.
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
class Thing | |
def foo | |
"foo" | |
end | |
def bar | |
puts foo | |
if foo.nil? | |
foo = "bar" | |
end | |
if foo.nil? | |
foo = "baz" | |
end | |
puts foo | |
end | |
end | |
Thing.new.bar | |
# >> foo | |
# >> baz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment