简体   繁体   English

Ruby中类单例方法的方法查找

[英]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

  1. Look in obj 's singleton class. 看看obj的单身课程。
  2. Look in the modules included by obj 's singleton class. 查看obj的单例类所包含的模块。
  3. Look in obj 's class. 看看obj的课。
  4. Look in the modules included by obj 's class 查看obj类所包含的模块
  5. repeat steps 3 and 4 on the class's superclass until found 在类的超类上重复步骤3和4,直到找到
  6. If never found, call 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: 实际的查找是:

  1. Start with obj 's singleton class. obj的单例类开始。
  2. Look for instance methods down the ancestor list: 在祖先列表中查找实例方法:
    • prepended modules (Ruby 2.0) 前置模块(Ruby 2.0)
    • the class itself 班级本身
    • included modules 包含模块
  3. Repeat #2 with superclass. 用超类重复#2。
  4. Repeat #1 but this time looking for 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM