On 11/14/05, Robert Evans <robert.evans / acm.org> wrote:
> Hi Ryan,
>
> Thanks for your help.
>
> I tried that, and it didn't work. Here is my irb transcript trying
> that. Is there another way to remove a constant? I thought I had seen
> one in the Pickaxe book, but maybe I was thinking of the module method.
>
> irb
> irb(main):001:0> FOO = "my symbol value"
> => "my symbol value"
> irb(main):002:0> remove_const(FOO)
> NoMethodError: undefined method `remove_const' for main:Object
>          from (irb):2
> irb(main):003:0> remove_const(:FOO)
> NoMethodError: undefined method `remove_const' for main:Object
>          from (irb):3
> irb(main):004:0> ??
>
>
> Any other ideas?

This is one of those odd methods that is hard to call. It is actually
a private method in Module, which means you must call it on a module
or class, and because it is private you must use send if you want to
call it from outside the class or module:

irb(main):001:0> FOO = "something"
=> "something"
irb(main):002:0> Object.const_defined?(:FOO)
=> true
irb(main):003:0> Object.send(:remove_const, :FOO)
=> "something"
irb(main):004:0> FOO
NameError: uninitialized constant FOO
        from (irb):4

But it is better to do something like this:

irb(main):005:0> class Test
irb(main):006:1> FOO = "something"
irb(main):007:1> end
=> "something"
irb(main):008:0> class Test
irb(main):009:1> FOO = "something else"
irb(main):010:1> end
(irb):9: warning: already initialized constant FOO
=> "something else"
irb(main):011:0> class Test
irb(main):012:1> remove_const(:FOO)
irb(main):013:1> FOO = "yet something else"
irb(main):014:1> end
=> "yet something else"

In other words you should call remove_const from inside the class
definition before re-creating it.

Ryan