Possible Duplicate:
Look up all descendants of a class in Ruby
那么,假设我们有:
class LivingBeing
class Animal
end
class Bacteria
end
class Virus
end
end
class Fungi < LivingBeing
end
如何检查 LivingBeing
有哪些子类?我知道我们有 Klass.ancestors
,但是查看祖先对立面的方法是什么?
核心 Ruby 语言中没有内置任何东西可以满足您的需求 - 您需要自己编写。这是一个示例方法 subclasses_of(class_name_here)
(如下),它将为您返回特定类的子类列表:
class Mammal
end
class Human < Mammal
end
class Dog < Mammal
end
def subclasses_of input
ObjectSpace.each_object(Class).select { |klass| klass < input }
end
subclasses_of(Mammal)
#=> [Human, Dog]
顺便说一句,这里有这个问题的答案:
http://dzone.com/snippets/objectsubclasses