Ruby Clasess

  • Thread starter Ruby Users Ruby Users
  • Start date
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

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]
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

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]

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).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top