Skip to content

Instantly share code, notes, and snippets.

@dragonfax
Created February 27, 2013 22:44
Show Gist options
  • Save dragonfax/5052542 to your computer and use it in GitHub Desktop.
Save dragonfax/5052542 to your computer and use it in GitHub Desktop.
give ruby its own version of perl's local() scoping, or "temporary-only values for existing variables."

I was digging around and found this little gem in a blog post on: http://banisterfiend.wordpress.com/2010/01/07/controlling-object-scope-in-ruby-1-9/

As an ex-perl hacker, I'm more partial to perl's local() rather than lisp's let()

def local
  yield
end

Thats it. Thats all there is too it. The magic is actually buried in all the rest that ruby already does.

So now you can

x = 1
local { |x|
 x = 3
 # work with x, its still 3.
}
x # is back to being 1 again. miraculously.

In ruby 1.9 you can even make it a little more suscinct.

local { |x=3|
  ...
}

go crazy, folks. go crazy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment