Skip to content

Instantly share code, notes, and snippets.

@brianium
Created December 29, 2012 21:45
Show Gist options
  • Save brianium/4409535 to your computer and use it in GitHub Desktop.
Save brianium/4409535 to your computer and use it in GitHub Desktop.
Tree solution for Ruby Day 2 HW
class Tree
attr_accessor :children, :node_name
def initialize(node = {})
(node.length == 1) && (@node_name = node.first[0]) || @node_name = 'root'
children = (@node_name == 'root') ? node : node[@node_name]
@children = []
children.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
nodes = {
'grandpa' => {
'dad' => {
'child1' => {},
'child2' => {}
},
'uncle' => {
'child3' => {},
'child4' => {}
}
}
}
tree = Tree.new(nodes)
tree.visit_all do |n|
puts n.node_name
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment