Aug 22

Ruby’s ObjectSpace: Subclasses

One of the (imho) lesser used pieces of the Ruby language is ObjectSpace.  In this article I’ll show one of the things you can do with it — get all the subclasses of a class.

ObjectSpace is almost a red-headed stepchild.  In JRuby you can even turn it off.  However, it does have its uses.

ObjectSpace has the following methods (apart from those in Object):

ObjectSpace does allow you to take an object’s id and change it to a reference:

The each_object method allows one to step through all the objects in memory, performing an operation with each. This is how we’re going to get a list of subclasses:

The code steps through the objects in ObjectSpace and returns an array of either the direct descendents, that is, ones directly subclassed from our object, or the entire tree of children.  By default it returns all the children (and their children (and …)).

So we can do the following:

So why would we want to do this? Well, for one, it’s a good learning tool. For another, imagine a case where we don’t know all of the classes which exist in an application, however, we do know that a good number of them are subclasses of the mysterious class X. We could pass a message to all of them — telling them it’s time for dinner, perhaps, by asking X about his children. Then we message the children, letting them know it’s dinner time:

Ok, so that last bit was contrived and I’m tuning into _why (not quite there, it’s still a bit static around the edges).

Anyone else have any uses for ObjectSpace?


2 pings

  1. Pit Capitain

    Hi Matt, if you search the ruby-talk archives you’ll find other, more efficient implementations for the direct == false case.

  2. Tomte

    Hi there,

    I found your code very helpful for my work. I’m working on a modular tool and I want to create one instance of all classes that are subclasses of another class. Since I don’t know of the existence of all those classes (I would need a configuration file or something like that, where each single one is specified), I searched exactly for the solution you provided here :). It works very well!!!

    Thanks for the good work 🙂

  3. Matt Williams

    I’m glad I was able to help!

  1. Nome do Jogo » Blog Archive » Rails Podcast Brasil - Episódio 29

    […] Ruby’s ObjectSpace: Subclasses […]

  2. Transparent Development » Blog Archive » How can I get a list of subclasses in Ruby?

    […] Ruby’s ObjectSpace: Subclasses […]

Leave a Reply

%d bloggers like this: