TransFS DevBlog / Article RSS Feed

Nov 15

How can I get a list of subclasses in Ruby?

By josh

I recently came across this useful tidbit from the Ramblings blog, posted back in August…

Ruby’s ObjectSpace: Subclasses

He came up with the the following code that uses ruby’s ObjectSpace for getting a list of subclasses for a given class:

module Subclasses
  # return a list of the subclasses of a class
  def subclasses(direct = false)
    classes = []
    if direct
      ObjectSpace.each_object(Class) do |c|
        next unless c.superclass == self
        classes << c
      end
    else
      ObjectSpace.each_object(Class) do |c|
        next unless c.ancestors.include?(self) and (c != self)
        classes << c
      end
    end
    classes
  end
end
 
Object.send(:include, Subclasses)

This allows you to do the following…

Enumerable.subclasses
=> [Struct::Tms, Dir, File, IO, Range, Struct, Hash, Array, String, StringIO, Socket, UNIXServer, UNIXSocket, UDPSocket, TCPServer, TCPSocket, IPSocket, BasicSocket, Struct::Group, Struct::Passwd, Zlib::GzipReader, Gem::SourceIndex]

Very cool. If you like it as much as I did… visit his blog and comment!

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Twitter

← Back to blog index

Leave a Comment