From: "Jesús Gabriel y Galán" Date: 2010-10-21T17:46:21+09:00 Subject: Re: scope when reopening method On Thu, Oct 21, 2010 at 10:36 AM, Rahul Kumar wrote: > Yes, you have misunderstood. "meth" already has access to its own > variables. > There is an application that creates an instance of My. > It also contains an array "arr". I'd like to refer to that array within > the reopened "meth". > I would also like to call some methods that are in my app from the > reopened method. OK. Clear. >   # i create an array that is not inside My class. Its in my > application. >   arr = [] > >   # this method belongs to my app, not to My class >   def do_something str >     puts str >   end > >   m = My.new >   def m.meth(str) >     # access some other object in application scope >     # arr can be instance variable or local variable in application >     arr << str >     do_something str # call some method in my app >   end > You could create a closure around your global scope. For that, you need to avoid keywords such as class and def, because those do not create closures, but create a new scope. You can try something like this: irb(main):001:0> arr = [1,2,3] => [1, 2, 3] irb(main):002:0> a = Object.new => # irb(main):003:0> class Object irb(main):004:1> def metaclass; class << self; self; end irb(main):005:2> end irb(main):006:1> end => nil irb(main):008:0> a.metaclass.instance_eval { define_method(:something) { "the array #{arr.inspect}"}} => # irb(main):009:0> a.something => "the array [1, 2, 3]" Jesus.