diff options
| author | Guillermo Ramos | 2012-03-29 19:33:22 +0200 | 
|---|---|---|
| committer | Guillermo Ramos | 2012-03-29 19:39:37 +0200 | 
| commit | d5fc25cac083e63c88a830bdcf7359f8a1dac643 (patch) | |
| tree | ab4cc595da944700d2ee0d8e9d63804b4a65ba26 /ruby/tree.rb | |
| parent | 3169c1929429aa79a5dd8bee7618e4ac6f84af63 (diff) | |
| download | 7l-d5fc25cac083e63c88a830bdcf7359f8a1dac643.tar.gz | |
[Ruby] Día 2
Diffstat (limited to 'ruby/tree.rb')
| -rwxr-xr-x | ruby/tree.rb | 36 | 
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} | 
