summaryrefslogtreecommitdiff
path: root/ruby/tree.rb
diff options
context:
space:
mode:
Diffstat (limited to 'ruby/tree.rb')
-rwxr-xr-xruby/tree.rb36
1 files changed, 36 insertions, 0 deletions
diff --git a/ruby/tree.rb b/ruby/tree.rb
new file mode 100755
index 0000000..364917e
--- /dev/null
+++ b/ruby/tree.rb
@@ -0,0 +1,36 @@
+#!/usr/bin/env ruby
+
+class Tree
+ attr_accessor :name, :children
+ def initialize(hash = {})
+ pair = hash.first
+ if pair
+ @name = pair[0]
+ @children = []
+ pair[1].each do |key, value|
+ @children.push(Tree.new( {key => value} ))
+ end
+ else
+ @name = nil
+ @children = nil
+ end
+ end
+
+ def visit_all(&block)
+ visit(&block)
+ children.each {|x| x.visit_all(&block) if x}
+ end
+
+ def visit(&block)
+ block.call self
+ end
+end
+
+ruby_tree = Tree.new({"Ruby" => {"Reia" => {"MacRuby" => {}}, "Waka" => {"Blr" => {}}}})
+
+puts "Visiting a node"
+ruby_tree.visit {|node| puts node.name}
+puts
+
+puts "Visiting entire tree"
+ruby_tree.visit_all {|node| puts node.name}