tags:

views:

73

answers:

1

You can dynamically define a class method for a class like so:

class Foo
end

bar = %q{def bar() "bar!" end}
Foo.instance_eval(bar)

But how do you do the opposite: remove/undefine a class method? I suspect Module's remove_method and undef_method methods might be able to be used for this purpose, but all of the examples I've seen after Googling for hours have been for removing/undefining instance methods, not class methods. Or perhaps there's a syntax you can pass to instance_eval to do this as well.

Thanks in advance.

+4  A: 
#!/usr/bin/ruby1.8

class Foo

  def Foo.bar
    puts "bar"
  end

end

Foo.bar

class <<Foo
  remove_method :bar
end

Foo.bar

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

Foo ----super----> Foo(eigenclass) ----super----> Object
                   def bar

That's why we have to open up Foo's eigenclass using class <<Foo to remove method bar.

Wayne Conrad
Bingo. Thanks Wayne!
Brian Ploetz