summaryrefslogtreecommitdiff
path: root/ruby/tree.rb
diff options
context:
space:
mode:
authorGuillermo Ramos2012-03-29 19:33:22 +0200
committerGuillermo Ramos2012-03-29 19:39:37 +0200
commitd5fc25cac083e63c88a830bdcf7359f8a1dac643 (patch)
treeab4cc595da944700d2ee0d8e9d63804b4a65ba26 /ruby/tree.rb
parent3169c1929429aa79a5dd8bee7618e4ac6f84af63 (diff)
download7l-d5fc25cac083e63c88a830bdcf7359f8a1dac643.tar.gz
[Ruby] Día 2
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}