Remove/undef a class method Remove/undef a class method ruby ruby

Remove/undef a class method


class Foo  def self.bar    puts "bar"  endendFoo.bar    # => barclass <<Foo  undef_method :barend# orclass Foo  singleton_class.undef_method :barendFoo.bar    # => undefined method `bar' for Foo:Class (NoMethodError)

When you define a class method like Foo.bar, Ruby puts it Foo's singleton class. Ruby can't put it in Foo, because then it would be an instance method. Ruby creates Foo's singleton class, sets the superclass of the singleton class to Foo's superclass, and then sets Foo's superclass to the singleton class:

Foo -------------> Foo(singleton class) -------------> Object        super      def bar             super

There are a few ways to access the singleton class:

  • class <<Foo,
  • Foo.singleton_class,
  • class Foo; class << self which is commonly use to define class methods.

Note that we used undef_method, we could have used remove_method. The former prevents any call to the method, and the latter only removes the current method, having a fallback to the super method if existing. See Module#undef_method for more information.


This also works for me (not sure if there are differences between undef and remove_method):

class FooendFoo.instance_eval do  def color    "green"  endendFoo.color # => "green"Foo.instance_eval { undef :color }Foo.color # => NoMethodError: undefined method `color' for Foo:Class


I guess I can't comment on Adrian's answer because I don't have enough cred, but his answer helped me.

What I found: undef seems to completely remove the method from existence, while remove_method removes it from that class, but it will still be defined on superclasses or other modules that have been extened on this class, etc.