class SomeClass
end
some_local_var = 5
sc = SomeClass.new
def sc.should_work_closure
puts some_local_var # how can I access "some_local_var", # doe开发者_开发问答sn't this work like a closure ?
end
sc.should_work_closure()
Line 9:in should_work_closure': undefined local variable or method
some_local_var' for # (NameError)
from t.rb:12
No, def
does not work like a closure.
To make sc
available in the def
you could make it a constant, make it global (usually a bad idea) or use define_method
with a block (which are closures).
However since you're not inside a class and define_method
is a method for classes (and modules), you can't just use it. You have to use class_eval
on the eigenclass of sc
to get inside the class.
Example:
class <<sc; self end.class_eval
define_method(:should_work_closure)
puts some_local_var
end
end
This will work, but it looks a bit scary. It usually is a bad idea to access local variables from the surrounding scope in method definitions.
精彩评论