class Node
Represents a single node in the trie.
Definitions
def initialize
Initialize a new trie node.
Implementation
def initialize
@values = nil
@children = Hash.new
end
def inspect
Generate a string representation of this node.
Signature
-
returns
String
A formatted string showing the number of children.
Implementation
def inspect
"#<#{self.class} #{@children.size} children>"
end
alias to_s inspect
Generate a string representation of the node.
attr_accessor :values
A mutable array of all values that terminate at this node.
Signature
-
attribute
Array | Nil
The values stored at this node, or nil if no values.
attr :children
A hash table of all children nodes, indexed by name.
Signature
-
attribute
Hash(String, Node)
Child nodes indexed by their path component.
def lookup(path, index = 0)
Look up a lexical path starting at this node.
Signature
-
parameter
path
Array(String)
The path to resolve.
-
parameter
index
Integer
The current index in the path (used for recursion).
-
returns
Node | Nil
The node at the specified path, or nil if not found.
Implementation
def lookup(path, index = 0)
if index < path.size
if child = @children[path[index]]
return child.lookup(path, index+1)
end
else
return self
end
end
def traverse(path = [], &block)
Traverse the trie from this node.
Invoke descend.call
to traverse the children of the current node.
Signature
-
parameter
path
Array(String)
The current lexical path.
-
yields
{|path, node, descend| ...}
Called for each node during traversal.
-
parameter
path
Array(String)
The current lexical path.
-
parameter
node
Node
The current node which is being traversed.
-
parameter
descend
Proc
The recursive method for traversing children.
-
parameter
Implementation
def traverse(path = [], &block)
descend = lambda do
@children.each do |name, node|
node.traverse([*path, name], &block)
end
end
yield(path, self, descend)
end