我将从以下示例开始:
class Foo
def self.bar
puts 12
end
end
Foo.singleton_methods # => [:bar]
Foo.ancestors # => [Foo, Object, Kernel, BasicObject]
在 Ruby 中,类也是对象。现在这里#bar
是一个单例方法Foo
。当你这样做时Foo.bar
,Foo
首先在它的单例类中搜索,然后在祖先链单例类中搜索。单例类是一种幽灵类,因此它在祖先链中不可见,但它存在。Foo.ancestors
它被语言设计者有意隐藏在输出中。单例方法由对象(此处为FOO)直接调用,在该对象上创建了单例(每个对象基础类)类。您不能创建单例类的实例。
这是一个证明:
Foo.singleton_class.new # can't create instance of singleton class (TypeError)
请记住,类的单例方法 say hereBar
也可用于其后代类(here Foo
)。因为 Bar 的元类变成了元类的超Foo
类,当你写的时候class Foo < Bar..
。
class Bar
def self.biz
puts 11
end
end
class Foo < Bar
def self.bar
puts 12
end
end
Bar.singleton_class # => #<Class:Bar>
Foo.singleton_class.superclass # => #<Class:Bar>