class Foo
def self.bar
puts "bar"
end
end
Foo.bar # => bar
class <<Foo
undef_method :bar
end
# or
class Foo
singleton_class.undef_method :bar
end
Foo.bar # => undefined method `bar' for Foo:Class (NoMethodError)
当你定义像Foo这样的类方法时.bar Ruby说这是Foo的单身班.Ruby不能将其放在Foo中,因为这样它将是一个实例方法.Ruby创建Foo的singleton类,将singleton类的超类设置为Foo的超类,然后将Foo的超类设置为singleton类:
Foo -------------> Foo(singleton class) -------------> Object
super def bar super
有几种方法可以访问singleton类:
class <<Foo
,
Foo.singleton_class
,
class Foo; class << self
,通常用于定义类方法.
注意,我们使用了undef_method
,我们可以使用remove_method
.前者阻止对该方法的任何调用,而后者只删除当前方法,如果存在超级方法,则可以回退到超级方法.更多信息请参见Module#undef_method.