5

Possible Duplicate:
Look up all descendants of a class in Ruby

So, let's say that we have:

class LivingBeing
  class Animal
  end

  class Bacteria
  end

  class Virus
  end
end

class Fungi < LivingBeing
end

How do I check what subclasses LivingBeing has? I know that we have Klass.ancestors but what's the method to see the opposite of ancestors?

Community
  • 1
  • 1
Thanks for all the fish
  • 1,671
  • 3
  • 17
  • 31

1 Answers1

3

There's nothing built into the core Ruby language that will do what you want - you'll need to write your own. Here's an example method subclasses_of(class_name_here) (below) that will return a list of subclasses of a particular class for you:

class Mammal
end

class Human < Mammal
end

class Dog < Mammal
end

def subclasses_of input
  ObjectSpace.each_object(Class).select { |klass| klass < input }
end

subclasses_of(Mammal)
 #=> [Human, Dog]

Btw, there's an answer to this question here:

http://dzone.com/snippets/objectsubclasses

Nat Ritmeyer
  • 5,634
  • 8
  • 45
  • 58
  • There is a subclasses method for the class. `Mammal.subclasses` gives `[Human, Dog]` – Prakash Murthy Oct 17 '12 at 22:35
  • Where? I tried the following: `> Mammal.subclasses NoMethodError: undefined method 'subclasses' for Mammal:Class from (irb):44 from /Users/nat/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in '
    '`. There's also no mention of it here: http://rdoc.info/stdlib/core/Module or here: http://rdoc.info/stdlib/core/Class
    – Nat Ritmeyer Oct 17 '12 at 22:39
  • Ah, I see... it's a rails thing: http://rdoc.info/gems/activesupport/Class#subclasses-instance_method – Nat Ritmeyer Oct 17 '12 at 22:48
  • 1
    Yup; I noticed it while in a rails console, and verified it is not there when in irb. Thanks for the links to the docs! – Prakash Murthy Oct 17 '12 at 22:53