Last active
August 29, 2015 14:04
-
-
Save tompave/e57975c3d4240703bc1d to your computer and use it in GitHub Desktop.
Scoping in Ruby blocks
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
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