Skip to content

Instantly share code, notes, and snippets.

@wwqrd
Created April 30, 2013 20:55
Show Gist options
  • Save wwqrd/5491867 to your computer and use it in GitHub Desktop.
Save wwqrd/5491867 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks - Ruby. tree.rb: Create a nested tree object using a hash as an input
class Tree
attr_accessor :children, :node_name
def initialize(tree)
tree.each { |name, branches|
@node_name = name
@children = []
branches.each_slice(1) { |branch|
@children.push(Tree.new(branch))
}
}
end
def visit_all(&block)
visit &block
children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
end
ruby_tree = Tree.new({
:grandad => {
:dad => {
:me => {},
:sister => {}
},
:uncle => {
:cousin => {}
}
}
})
puts "Visiting a node"
ruby_tree.visit {|node| puts node.node_name}
puts
puts "visiting entire tree"
ruby_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