Remove Nested module constant in ruby


1 min read

You might have seen this solution.

Object.send(:remove_const, :ExampleClass)

But what if you want to remove namespaced classes in Ruby. You can use the same method, but instead of Object use the parent module where your class is nested.

module App
  module ExampleClass

Object.send(:remove_const, :App::ExampleClass) ### โŒ Does not work!!!!

App.send(:remove_const, :ExampleClass) # โœ… This works

Now before removing the const, you can check if the constant is defined or not.

if App.const_defined?(:ExampleClass)
  App.send(:remove_const, :ExampleClass)

Perfect! ๐Ÿ„