Ruby Clasess

How do I get all the classes that descend from a parent class ? I found
solution on
http://stackoverflow.com/questions/2393697/look-up-all-descendants-of-a-class-in-ruby.

But I want to know, is there a standard method or not?

No there is not.

7stud – wrote in post #1000123:

No there is not.

THX

class Animal

def self.inherited(subclass)
children << subclass
end

def self.children
@children ||= []
end

def self.descendants
children.map do |child|
[child].concat child.descendants
end.flatten
end

end

Dog = Class.new Animal
Cat = Class.new Animal
Tabby = Class.new Cat

RUBY_VERSION # => “1.9.2”
Animal.children # => [Dog, Cat]
Animal.descendants # => [Dog, Cat, Tabby]

Cat.descendants # => [Tabby]

On Sun, May 22, 2011 at 12:11 PM, Josh C. [email protected]
wrote:

def self.descendants

RUBY_VERSION # => “1.9.2”
Animal.children # => [Dog, Cat]
Animal.descendants # => [Dog, Cat, Tabby]

Cat.descendants # => [Tabby]

Accidentally pasted the code over the entire response >.<

I meant to say you could whip something up without too much effort (as
7stud
said, there is no standard way).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs