antimac.org
Dan's homepage

Ruby has a neat method available for enumerating all constants defined within a namespace/class/module – constants().  As all classes inherit from the Object class, one can call Object.constants() to get a list of constants which can then be filtered into something useful.

For example, I had defined a bunch of *Parser classes in my code.  Rather than manually instantiate each one, I used the following to iterate over them automagically.

Object.constants().each do |const|
  if !is_my_class?(const)
    next
  end

  obj = Module.const_get(const).new()
  # do stuff here
  obj = nil
end

Simply define is_my_class?() and you’re good to go.

Leave a Reply