Skip to content

Instantly share code, notes, and snippets.

@maxjacobson
Created March 19, 2013 21:45
Show Gist options
  • Save maxjacobson/5200431 to your computer and use it in GitHub Desktop.
Save maxjacobson/5200431 to your computer and use it in GitHub Desktop.
family tree
class Node
attr_accessor :name, :children
def initialize (name)
@name = name
@children = Hash.new
end
def add_children(*names)
names.each do |name|
@children[name] = Node.new(name)
end
end
def print_children(depth = 0)
puts "#{" " * depth}* #{@name} has #{@children.length} child#{"ren" if @children.length != 1}"
@children.each_value do |child|
child.print_children(depth+1)
end
end
end
grandma = Node.new "Anita"
grandma.add_children "Seth", "Louie", "Beth", "Frannie", "Debbie"
seth = grandma.children["Seth"]
seth.add_children "Jessica", "Max", "Gaby"
louie = grandma.children["Louie"]
louie.add_children "Jake", "Ben"
beth = grandma.children["Beth"]
beth.add_children "Alex", "Becca", "Samantha"
frannie = grandma.children["Frannie"]
frannie.add_children "Jack", "Dan", "Jenna"
jack = frannie.children["Jack"]
jack.add_children "Luke"
grandma.print_children
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment