Search this site


Metadata

Articles

Projects

Presentations

Ruby: Finding subclasses in your world

Use the ObjectSpace class to find all ancestors of a given class.
class Foo; end
class Bar < Foo; end
class Baz < Foo; end

subclasses = ObjectSpace.each_object(Class).select do |klass|
  klass.ancestors.include?(Foo) and klass != Foo
end

# prints "[Baz, Bar]"
puts subclasses
Of course, you could always override Class#inherited instead, but if you don't want to override methods, the above is a reasonable choice.