tags:

views:

32

answers:

1
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", # doesn't this work like a closure ?
end

sc.should_work_closure()

Line 9:in should_work_closure': undefined local variable or methodsome_local_var' for # (NameError) from t.rb:12

A: 

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.

sepp2k
in 1.9.2 you can simply go: `sc.define_singleton_method(:should_work_closure) { puts some_local_var }1
banister