Skip to content

Instantly share code, notes, and snippets.

@tompave
Last active August 29, 2015 14:04
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 tompave/e57975c3d4240703bc1d to your computer and use it in GitHub Desktop.
Save tompave/e57975c3d4240703bc1d to your computer and use it in GitHub Desktop.
Scoping in Ruby blocks
def set_context(c)
@context = c
end
def context
@context
end
def with_context(cont, &block)
original_cont = context
set_context cont
block.call
ensure
set_context original_cont
end
set_context :base
foo = nil
with_context("hello") do
foo = context.upcase
bar = context.reverse
end
foo
# => "HELLO"
bar
# NameError: undefined local variable or method `bar' for main:Object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment