我知道您在问如何在继承中执行此操作,但是您可以通过在类中使用名称间隔(Class或Module)直接在Ruby中实现此功能
module DarthVader
module DarkForce
end
BlowUpDeathStar = Class.new(StandardError)
class Luck
end
class Lea
end
end
DarthVader.constants # => [:DarkForce, :BlowUpDeathStar, :Luck, :Lea]
DarthVader
.constants
.map { |class_symbol| DarthVader.const_get(class_symbol) }
.select { |c| !c.ancestors.include?(StandardError) && c.class != Module }
# => [DarthVader::Luck, DarthVader::Lea]
ObjectSpace与其他解决方案所建议的每个类进行比较相比,这种方法要快得多。
如果您在继承中非常需要此功能,则可以执行以下操作:
class DarthVader
def self.descendants
DarthVader
.constants
.map { |class_symbol| DarthVader.const_get(class_symbol) }
end
class Luck < DarthVader
# ...
end
class Lea < DarthVader
# ...
end
def force
'May the Force be with you'
end
end
此处的基准:http :
//www.eq8.eu/blogs/13-ruby-ancestors-descendants-and-other-annoying-relatives
更新
最后,您要做的就是
class DarthVader
def self.inherited(klass)
@descendants ||= []
@descendants << klass
end
def self.descendants
@descendants || []
end
end
class Foo < DarthVader
end
DarthVader.descendants #=> [Foo]
谢谢@saturnflyer的建议