Вопрос

class Taco
  # . . .
end

Get ancestor chain:

Taco.ancestors
 #=> [Taco, Object, Kernel, BasicObject]

Say I want to find the "parent" class and it's ancestor chain for a ruby defined method. How would I go about doing that?

E.g. method_missing.parent.ancestors

And if everything is supposed to inherit from BasicObject why doesn't Kernel?

Object.ancestors
 #=> [Object, Kernel, BasicObject]

Kernel.ancestors
 #=> [Kernel]

BasicObject.ancestors
 #=> [BasicObject]

Also Class inherits from Class and Module but why does my Taco class ancestor's chain not inherit from them and instead inherits directly from Object forward?

Class.ancestors
#=> [Class, Module, Object, Kernel, BasicObject]
Это было полезно?

Решение 2

Specifically regarding your question: "Also Class inherits from Class and Module but why does my Taco class ancestor's chain not inherit from them and instead inherits directly from Object forward?"

Taco is an instance of Class, but its superclass is Object. An instance relationship and a superclass relationship are 2 completely different things.

For example: imagine you create a class Animal with a subclass Dog. Animal.new will give you an object which is an instance of Animal. The Dog class is not an instance of Animal (it is not itself an animal -- rather, it defines a type of animal). Its superclass is Animal.

Every object is an instance of some class -- call class to find out which one. But not all objects have a superclass -- only instances of Class do.

Additionally, Class does not inherit from Class. That is impossible. All classes appear at the beginning of their own ancestors, but that doesn't mean they inherit from themselves. That is just how the ancestors method works.

Другие советы

You are looking for owner.

method(:puts).owner 
  #=> Kernel
method(:puts).owner.ancestors
  #=> [Kernel]

Back to your taco example:

class Taco
  def self.eat
    "YUM"
  end
end

Taco.method(:eat).owner
  #=> #<Class:Taco>
Taco.method(:eat).owner.ancestors
  #=> [Class, Module, Object, PP::ObjectMixin, Kernel, BasicObject]

Kernel is an instance of module. Check this out:

Kernel.class.ancestors
  #=> [Module, Object, PP::ObjectMixin, Kernel, BasicObject]

Here is some further reading on the ruby object model if you're interested. Also, here's an image stolen from google images that may help solidify those concepts.

ruby object model

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top