Skip to content

Instantly share code, notes, and snippets.

@beautifulcode
Created February 14, 2014 17:41
Show Gist options
  • Save beautifulcode/9005497 to your computer and use it in GitHub Desktop.
Save beautifulcode/9005497 to your computer and use it in GitHub Desktop.
class Person
def initialize(name, children = [])
@children = children
@descendents = []
@name = name
end
def get_all_descendents
children.each do |child|
@descendents << child
@descendents << child.get_all_descendents if child.children.size > 0
end
@descendents.flatten.uniq
end
def children
@children || []
end
def to_s
@name
end
end
son = Person.new('Son')
father = Person.new('Father', [son])
grandfather = Person.new('GrandFather', [father])
granduncle = Person.new('GrandUncle', [])
great_grandfather = Person.new('GreatGrandfather', [grandfather, granduncle])
puts great_grandfather.get_all_descendents
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment