blob: 364917e4316884e1ddfc28b5f85afeefe0cbab75 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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}
|