Joined May 2014
·

Andreas Rayo Kniep

San Francisco
·
·

As far as I understand it, methods and Method objects are no closures.

By definition, a closure (unlike a normal function) has access to non-local variables even when invoked outside its immediate lexical scope.
In other words: A closure "remembers" all variables that were in scope when the function was created.
In the following example, `outsideĀ“ should be that non-local variable:

# Compare outputs, eg. in IRB:

outside = 7

# blocks are closures:
[1,2,3].map {|e| e+outside}
#=> [8,9,10]

# procs are closures:
proc {|e| e+outside}.call(4)
#=> 11

# lambdas are closures:
->(e) {e+outside}.call(5)
#=> 12

### but... ####################################################
# normal functions are NO closures
def fun(e)
  e + outside
end
fun(6)
#=> NameError: undefined local variable or method `outside' for main:Object

# methods are NO closures
method(:fun).call(7)
#=> NameError: undefined local variable or method `outside' for main:Object
Achievements
1 Karma
0 Total ProTip Views