Skip to content

Instantly share code, notes, and snippets.

@jbuda
Created October 19, 2013 21:05
Show Gist options
  • Save jbuda/7061547 to your computer and use it in GitHub Desktop.
Save jbuda/7061547 to your computer and use it in GitHub Desktop.
Ruby - Day 2 - Seven Languages in Seven Weeks
# update the tree initialiser to accept a nested structure with hashes and arrays
class Tree
attr_accessor :children, :node_name
def initialize(tree)
@node_name = tree.keys()[0]
@children = []
tree[tree.keys()[0]].each do |k,v|
@children.push(Tree.new({k=>v}))
end
end
def visit_all(&block)
visit &block
children.each { |c| c.visit_all &block }
end
def visit(&block)
block.call self
end
end
tree = Tree.new({'grandpa'=>{'dad'=>{'child 1'=>{},'child 2'=>{}},'uncle'=>{'child 3'=>{},'child 4'=>{}}}})
tree.visit_all {|node| puts node.node_name }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment