删除/取消定义类方法 [英] Removing/undefining a class method

查看:95
本文介绍了删除/取消定义类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以像这样为类动态定义类方法:

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)

但是您如何相反: 删除/取消定义 一个类方法?我怀疑Module的remove_methodundef_method方法可能可以用于此目的,但是我在Google搜索了几个小时后看到的所有示例都是用于删除/未定义 instance 方法的,不是类方法.也许有一种语法可以传递给instance_eval来完成.

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.

谢谢.

推荐答案

#!/usr/bin/ruby1.8

class Foo

  def Foo.bar
    puts "bar"
  end

end

Foo.bar    # => bar

class <<Foo
  remove_method :bar
end

Foo.bar    # => undefined method `bar' for Foo:Class (NoMethodError)

当您定义Foo.bar之类的类方法时,Ruby会将其称为Foo的本征类. Ruby不能将其放在Foo中,因为那样的话它将是一个实例方法. Ruby创建Foo的本征类(也称为单身类"),将本征类的超类设置为Foo的超类,然后将Foo的超类设置为本征类:

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 -------------> Foo(eigenclass) -------------> Object
        super      def bar             super

这就是为什么我们必须使用class <<Foo打开Foo的本征类以删除方法栏的原因.

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

这篇关于删除/取消定义类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆