问题描述
我的印象是 obj.method
导致 ruby 如此寻找 method
:
I was under the impression that obj.method
caused ruby to look for method
thusly:
- 查看
obj
的单例类. - 查看
obj
的单例类包含的模块. - 查看
obj
的类. - 查看
obj
的类包含的模块 - 在类的超类上重复第 3 步和第 4 步,直到找到
- 如果未找到,则对原始对象
obj
调用method_missing
.
- Look in
obj
's singleton class. - Look in the modules included by
obj
's singleton class. - Look in
obj
's class. - Look in the modules included by
obj
's class - repeat steps 3 and 4 on the class's superclass until found
- If never found, call
method_missing
on the original object,obj
.
在这个模型下,搜索方法的唯一单例类是原始接收者的单例类,obj
.但是,该模型无法解释子类可以访问其超类的单例方法这一事实.例如
Under this model, the only singleton class searched for the method is the singleton class of the original receiver, 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"
我很困惑,因为我相信这意味着 Foo
的单例类在某个时候会搜索方法 foo
.然而,在上面的模型下,我希望只有 Bar
的单例类会被搜索 foo
.如果做不到这一点,我希望 ruby 查看 Bar
的类,Class
,然后继续爬上超类链(跳过 Foo
和它的单例类完全).
I'm confused because I believe this means that Foo
's singleton class is at some point searched for the method foo
. However, under the model above, I would expect that only Bar
's singleton class would be searched for 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 方法查找的理解中缺少什么来解释一个类可以访问其超类的单例方法的事实?
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?
推荐答案
子类化时,不仅 Bar.superclass
设置为 Foo
,同样适用于单例类:
When subclassing, not only is Bar.superclass
set to Foo
, but the same holds true for the singleton classes:
Bar.singleton_class.superclass == Foo.singleton_class # => true
所以你并没有真正感到困惑.实际查找是:
So you're not really confused. The actual lookup is:
- 从
obj
的单例类开始. - 在祖先列表中查找实例方法:
- 前置模块 (Ruby 2.0)
- 类本身
- 包含的模块
这篇关于Ruby 中类单例方法的方法查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!