Skip to content

Instantly share code, notes, and snippets.

@travisdahlke
Last active December 26, 2015 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travisdahlke/7107244 to your computer and use it in GitHub Desktop.
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.
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