Created
June 11, 2011 16:43
-
-
Save mcary/1020737 to your computer and use it in GitHub Desktop.
Lexical and dynamic scoping in Ruby
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
# Within the context of a single instance, instance variables have dynamic | |
# scoping semantics. But local variables do not; they are lexically scoped. | |
class DynamicScopingExample | |
def some_method | |
@x = :foo | |
some_other_method | |
end | |
def some_other_method | |
@x | |
end | |
end | |
p DynamicScopingExample.new.some_method | |
# prints :foo | |
class LexicalScopingExample | |
def some_method | |
x = :foo | |
some_other_method | |
end | |
def some_other_method | |
x | |
end | |
end | |
p LexicalScopingExample.new.some_method | |
# raises undefined local variable or method `x' for #<LexicalScopingExample:0x100565ff8> (NameError) |
What you cite as dynamic scope isn't dynamic scope. It's an assignment, a side-effect, that will live on after the scope ends. Here's proof: if this were true dyamic scope (or, for that matter, lexical scope), then calling DynamicScopingExample.new.some_method
would return :foo
. However, it returns :bar
even though some_other_method
scope is long gone.
class DynamicScopingExample
def some_method
@x = :foo
some_other_method
@x
end
def some_other_method
@x = :bar
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Are instance variables actually lexically scoped or do they just appear that way because the calling environment is the same as the defining environment?