[英]Method lookup for class singleton methods in Ruby
I was under the impression that obj.method
caused ruby to look for method
thusly: 我的印象是obj.method
导致ruby寻找method
:
obj
's singleton class. 看看obj
的单身课程。 obj
's singleton class. 查看obj
的单例类所包含的模块。 obj
's class. 看看obj
的课。 obj
's class 查看obj
类所包含的模块 method_missing
on the original object, obj
. 如果从未找到,请在原始对象obj
上调用method_missing
。 Under this model, the only singleton class searched for the method is the singleton class of the original receiver, obj
. 在这个模型下,搜索该方法的唯一单例类是原始接收器的单例类obj
。 However, this model can't explain the fact that a subclass can access its superclass's singleton methods. 但是,这个模型无法解释子类可以访问其超类的单例方法的事实。 For example 例如
class Foo
def self.foo
"foo"
end
end
class Bar < Foo
end
Bar.foo #=> "foo"
I'm confused because I believe this means that Foo
's singleton class is at some point searched for the method foo
. 我很困惑因为我相信这意味着Foo
的单例类在某些时候搜索了方法foo
。 However, under the model above, I would expect that only Bar
's singleton class would be searched for foo
. 但是,在上面的模型中,我希望只有Bar
的单例类才会被搜索到foo
。 Failing that, I would expect ruby to look in Bar
's class, Class
, and then continue crawling up the superclass chain (skipping Foo
and its singleton class completely). 如果做不到这一点,我希望ruby可以查看Bar
的类Class
,然后继续爬上超类链(完全跳过Foo
及其单例类)。
So my question: what is missing from my understanding of Ruby method lookup which explains the fact that a class can access its superclass's singleton methods? 所以我的问题是:我对Ruby方法查找的理解缺少什么,这解释了一个类可以访问其超类的单例方法的事实?
When subclassing, not only is Bar.superclass
set to Foo
, but the same holds true for the singleton classes: 子类化时,不仅将Bar.superclass
设置为Foo
,而且对于单例类也是如此:
Bar.singleton_class.superclass == Foo.singleton_class # => true
So you're not really confused. 所以你真的不会感到困惑。 The actual lookup is: 实际的查找是:
obj
's singleton class. 从obj
的单例类开始。 method_missing
重复#1,但这次寻找method_missing
It's pretty straightforward. 这很简单。 Or not really, but anyhow: 或者不是真的,但无论如何:
The metaclass of the superclass is the superclass of the metaclass.
Where "metaclass" is really "singleton class". “元类”真的是“单身类”。 What's missing in your model is Bar.superclass
inherits Foo.superclass
. 模型中缺少的是Bar.superclass
继承Foo.superclass
。 Plain and simple :) 干净利落 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.