Skip to content

Instantly share code, notes, and snippets.

@nazgob
Created July 1, 2010 12:54
Show Gist options
  • Save nazgob/459917 to your computer and use it in GitHub Desktop.
Save nazgob/459917 to your computer and use it in GitHub Desktop.
tree like structure with blocks and recursion
#!/usr/bin/ruby
class Tree
attr_accessor :children, :node_name
def initialize(name, children)
@children = children
@node_name = name
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("Ruby", [Tree.new("Reia", []), Tree.new("MacRuby", [])])
puts "visiting a node"
puts 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