How to undefine class in Ruby?

class Foo; end
# => nil
Object.constants.include?(:Foo)
# => true
Object.send(:remove_const, :Foo)
# => Foo
Object.constants.include?(:Foo)
# => false
Foo
# NameError: uninitialized constant Foo

EDIT Just noticed your edit, removing the constant is probably not the best way to achieve what you’re looking for. Why not just move one of the Contact classes into a separate namespace.

EDIT2 You could also rename your class temporarily like this:

class Foo
  def bar
    'here'
  end
end

TemporaryFoo = Foo
Object.send(:remove_const, :Foo)
# do some stuff
Foo = TemporaryFoo
Foo.new.bar #=> "here"

Again, the trouble with this is that you’ll still have the newer Contact class so you’ll have to remove that again. I would really recommend name-spacing your classes instead. This will also help you avoid any loading issues

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)