From: Roland Swingler Date: 2007-01-07T01:15:14+09:00 Subject: Getting existing context when defining a singleton method (class << obj) Hi I'm fairly new to this "meta-programming" thing, so excuse me if I get my terminology wrong. Is there any way of getting access to the exisiting context when using class << obj or otherwise creating a singleton method? For example of what I mean - I have a method that returns a Proc: def foo() local_var = "Bar" Proc.new { local_var } end x = foo() x.call --> returns "Bar", 'remembering' the local context and I want to something similar with methods defined using class << obj: class MyObject end def foo(my_object_instance) local_var = "Bar" class << my_object_instance define_method(:a_method) { local_var } end end o = MyObject.new foo(o) o.a_method --> throws an error, complaining about missing local variable If I just wanted to assign this method to the class then I think I could do the following in foo: my_object_instance.class.send(:define_method, :a_method) { local_var } But I want to define a singleton method, and I don't think you can get access to an object instance's virtual class in a similar way? Any help with this much appreciated, TIA Roland