On Mon, 29 Jan 2001, Mark Slagell wrote:

> Could somebody show me a short working example? or tell me what's wrong
> here?
> 
>   class Groucho
>     def initialize
>       print "Hello, I must be going.\n"
>     end
>   end
>   m = Groucho.new
>   remove_const(:Groucho)
> 
> ...yields:
> 
>  Hello, I must be going.
>  rc:8: undefined method `remove_const' for #<Object:0x45aa658>
> (NameError)
> 
As Guy already pointed out its because remove_const is private. However
note that removing the const will not remove the class from the
ObjectSpace until all references to it is lost. Try the code:

  class Groucho
    def initialize
      print "Hello, I must be going.\n"
    end
  end
  m = Groucho.new
  class Object
    remove_const("Groucho")
  end

  # Now you can't create a new Groucho
  begin
    m2 = Groucho.new
  rescue NameError
    puts "Failing to create an instance of Groucho...!"
  end
  
  # but note that it is still in the object space since there is reference
to
  # it (m).
  ObjectSpace.each_object(m.class) do |kl|
    puts "ObjSpace search 1: Found object of type: #{kl.type}"
    # Get it back with: Groucho = kl.type
  end

  # but it will not be there after the reference to m is lost
  m, found = nil, nil
  # GC needed?!
  ObjectSpace.each_object(m.class) do |kl|
    found = true
    puts "ObjSpace search 2: Still Found object of type: #{kl.type}"
  end
  puts "ObjSpace search 2: Couldn't find object of type Groucho!" unless
found

So if you're really nuts you can get it back before last reference
disappears... ;-)

Regards,

Robert