views:

46

answers:

1

Suppose I make a module as follows:

m = Module.new do
  class C
  end
end

Three questions:

  • Other than a reference to m, is there a way I can access C and other things inside m?

  • Can I give a name to the anonymous module after I've created it (just as if I'd typed "module ...")?

  • How do I delete the anonymous module when I'm done with it, such that the constants it defines are no longer present?

+6  A: 

Three answers:

  • Yes, using ObjectSpace. This code makes c refer to your class C without referencing m:

    c = nil  
    ObjectSpace.each_object { |obj|  
      c = obj if (Class === obj and obj.name =~ /::C$/)  
    }
    

    Of course this depends on there being no other classes named C anywhere in the program, but you get the idea.

  • Yes, sort of. If you just assign it to a constant, like M = m, then m.name will return "M" instead of nil, and references like M::C will work. Actually, when I do this and type M::C in irb, I get #<Module:0x9ed509c>::C, but maybe that's a bug.

  • I think it should be garbage collected once there are no references to it, i.e. when there are no instances or subtypes of m or C, and m is set to a different value or goes out of scope. If you assigned it to a constant as in the above point, you would need to change it to a different value too (though changing constants is generally ill-advised).
wdebeaum