Skip to content

Instantly share code, notes, and snippets.

@MarkBennett
Created August 17, 2012 02:26
Show Gist options
  • Save MarkBennett/3375397 to your computer and use it in GitHub Desktop.
Save MarkBennett/3375397 to your computer and use it in GitHub Desktop.
How do Ruby closures work?
greeting = "Hello"
def greeter
puts greeting
end
greeter
# undefined local variable or method `greeting' for main:Object (NameError)
@davidrichards
Copy link

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:

  1. a method creates a new binding, so it doesn't have access to the closure around it
  2. a proc (lambda, block, all that stuff) does inherit the closure around it
  3. methods don't pass their closures between them

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.

@stormbrew
Copy link

Methods are not lexical closures, so I'm not sure what you're asking here?

@avdi
Copy link

avdi commented Aug 17, 2012

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