Skip to content

Instantly share code, notes, and snippets.

@mcary
Created June 11, 2011 16:43
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 mcary/1020737 to your computer and use it in GitHub Desktop.
Save mcary/1020737 to your computer and use it in GitHub Desktop.
Lexical and dynamic scoping in Ruby
# 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)
@watsoncj
Copy link

watsoncj commented Oct 7, 2013

Are instance variables actually lexically scoped or do they just appear that way because the calling environment is the same as the defining environment?

@dcmorse
Copy link

dcmorse commented Jun 25, 2016

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