ruby提供了显示层次结构调用的方法吗?

时间:2022-02-25 20:47:12

That's all, i want to see what are the clases that inherits a fixed class. There is a method for this in RUBY?

这就是所有的,我想知道什么是继承固定类的clases。在RUBY中有这样的方法吗?

Aptana offers an option that shows this, but is there any method?

Aptana提供了一个显示此选项的选项,但是有什么方法吗?

Thanks

谢谢

2 个解决方案

#1


22  

Are you asking to see all the ancestors of a class, or the descendants? For ancestors, use:

你是想看看一个阶级的所有祖先,还是想看看他们的后代?对于祖先,使用:

Class.ancestors

There is no comparable method "out of the box" for descendants, however. You can use ObjectSpace, as below, but it's slow and may not be portable across Ruby implementations:

然而,对于后代来说,没有类似的“开箱即用”方法。您可以使用ObjectSpace,如下所示,但是它速度很慢,并且可能不能跨Ruby实现移植:

ObjectSpace.each_object(Class) do |klass| 
  p klass if klass < StandardError
end

EDIT:

编辑:

One can also use the Class#inherited hook to track subclassing. This won't catch any subclasses created before the tracking functionality is defined, however, so it may not fit your use case. If you need to use that information programmatically on classes defined inside your application, however, this may be the way to go.

还可以使用类#继承钩子来跟踪子类。但是,这不会捕获在定义跟踪功能之前创建的任何子类,因此它可能不适合您的用例。但是,如果您需要在应用程序中定义的类上以编程方式使用该信息,那么可以采用这种方法。

#2


6  

Module#ancestors

模块#祖先

Example:

例子:

class Foo
end

class Bar < Foo
end

Bar.ancestors # => [Bar, Foo, Object, Kernel]

#1


22  

Are you asking to see all the ancestors of a class, or the descendants? For ancestors, use:

你是想看看一个阶级的所有祖先,还是想看看他们的后代?对于祖先,使用:

Class.ancestors

There is no comparable method "out of the box" for descendants, however. You can use ObjectSpace, as below, but it's slow and may not be portable across Ruby implementations:

然而,对于后代来说,没有类似的“开箱即用”方法。您可以使用ObjectSpace,如下所示,但是它速度很慢,并且可能不能跨Ruby实现移植:

ObjectSpace.each_object(Class) do |klass| 
  p klass if klass < StandardError
end

EDIT:

编辑:

One can also use the Class#inherited hook to track subclassing. This won't catch any subclasses created before the tracking functionality is defined, however, so it may not fit your use case. If you need to use that information programmatically on classes defined inside your application, however, this may be the way to go.

还可以使用类#继承钩子来跟踪子类。但是,这不会捕获在定义跟踪功能之前创建的任何子类,因此它可能不适合您的用例。但是,如果您需要在应用程序中定义的类上以编程方式使用该信息,那么可以采用这种方法。

#2


6  

Module#ancestors

模块#祖先

Example:

例子:

class Foo
end

class Bar < Foo
end

Bar.ancestors # => [Bar, Foo, Object, Kernel]