Created
August 17, 2012 02:26
-
-
Save MarkBennett/3375397 to your computer and use it in GitHub Desktop.
How do Ruby closures work?
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
greeting = "Hello" | |
def greeter | |
puts greeting | |
end | |
greeter | |
# undefined local variable or method `greeting' for main:Object (NameError) |
Methods are not lexical closures, so I'm not sure what you're asking here?
If you want a lexical closure you need to use define_method
instead.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wish I knew all the rules for ruby closures. I tend to use instance variables for this kind of thing. To start to edge towards some insight, I did this: https://gist.github.com/3375580
I think this is what I know about this:
Basically, Ruby closures are really different than JavaScript, which would let you share/inherit closures a bit differently. I did find a description about this kind of thing in The Ruby Way, section 1.5.4, if you happen to have access to that.