Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created October 21, 2010 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/638085 to your computer and use it in GitHub Desktop.
Save rklemme/638085 to your computer and use it in GitHub Desktop.
Example tree implementation
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