在 Ruby 中查找一个类的所有后代 [英] Look up all descendants of a class in Ruby
本文介绍了在 Ruby 中查找一个类的所有后代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以轻松地在 Ruby 中提升类层次结构:
I can easily ascend the class hierarchy in Ruby:
String.ancestors # [String, Enumerable, Comparable, Object, Kernel]
Enumerable.ancestors # [Enumerable]
Comparable.ancestors # [Comparable]
Object.ancestors # [Object, Kernel]
Kernel.ancestors # [Kernel]
有没有办法降低层次结构?我想这样做
Is there any way to descend the hierarchy as well? I'd like to do this
Animal.descendants # [Dog, Cat, Human, ...]
Dog.descendants # [Labrador, GreatDane, Airedale, ...]
Enumerable.descendants # [String, Array, ...]
但似乎没有 descendants
方法.
(出现这个问题是因为我想在 Rails 应用程序中找到从基类派生的所有模型并列出它们;我有一个可以处理任何此类模型的控制器,我希望能够添加新模型而无需修改控制器.)
(This question comes up because I want to find all the models in a Rails application that descend from a base class and list them; I have a controller that can work with any such model and I'd like to be able to add new models without having to modify the controller.)
推荐答案
这是一个例子:
class Parent
def self.descendants
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
end
class Child < Parent
end
class GrandChild < Child
end
puts Parent.descendants
puts Child.descendants
puts Parent.descendants 给你:
puts Parent.descendants gives you:
GrandChild
Child
puts Child.descendants 给你:
puts Child.descendants gives you:
GrandChild
这篇关于在 Ruby 中查找一个类的所有后代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文