Created
October 21, 2010 07:52
-
-
Save rklemme/638085 to your computer and use it in GitHub Desktop.
Example tree implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pp' | |
Node = Struct.new :value, :parent, :children do | |
def initialize(value = nil, parent = nil) | |
self.value = value | |
self.children = [] | |
yield self if block_given? | |
end | |
def add(child) | |
children << child | |
child.parent = self | |
end | |
alias << add | |
def each_child(&b) | |
b[self] | |
children.each do |ch| | |
ch.each_child(&b) | |
end | |
self | |
end | |
def root | |
n = self | |
n = n.parent while n.parent | |
n | |
end | |
def doc_each_child(&b) | |
root.each_child(&b) | |
self | |
end | |
end | |
foo = nil | |
tree = Node.new(1) {|x1| | |
x1 << Node.new(2) {|x2| | |
x2 << Node.new(3) << Node.new(4) | |
foo = Node.new(5) | |
x2 << foo | |
} << Node.new(6) | |
} | |
# XPath '*' | |
foo.each_child do |ch| | |
printf "Node %5s\n", ch.value | |
end | |
puts '-----------------' | |
# XPath '//*' | |
foo.doc_each_child do |ch| | |
printf "Node %5s\n", ch.value | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment