lib/rambling/trie/node.rb in rambling-trie-0.8.1 vs lib/rambling/trie/node.rb in rambling-trie-0.9.0
- old
+ new
@@ -1,42 +1,39 @@
module Rambling
module Trie
# A representation of a node in the Trie data structure.
class Node
- extend Forwardable
+ extend ::Forwardable
- delegate [:[], :[]=, :delete, :has_key?] => :children_tree
+ delegate [
+ :[],
+ :[]=,
+ :delete,
+ :has_key?
+ ] => :children_tree
- include Compressor
- include Branches
- include Enumerable
- include Inspector
+ include Rambling::Trie::Compression
+ include Rambling::Trie::Enumerable
+ include Rambling::Trie::Inspector
# Letter or letters corresponding to this node.
# @return [Symbol, nil] the corresponding letter(s) or nil.
attr_reader :letter
# Children nodes.
# @return [Hash] the children_tree hash, consisting of :letter => node.
- attr_reader :children_tree
+ attr_accessor :children_tree
# Parent node.
# @return [Node, nil] the parent node or nil for the root element.
attr_accessor :parent
# Creates a new Node.
- # @param [String, nil] word the word from which to create this Node and his branch.
# @param [Node, nil] parent the parent of this node.
- def initialize word = nil, parent = nil
+ def initialize parent = nil
self.parent = parent
self.children_tree = {}
-
- unless word.nil? || word.empty?
- self.letter = word.slice! 0
- self.terminal = word.empty?
- self << word
- end
end
# String representation of the current node, if it is a terminal node.
# @return [String] the string representation of the current node.
# @raise [InvalidOperation] if node is not terminal or is root.
@@ -50,36 +47,42 @@
def children
children_tree.values
end
# If the current node is the root node.
- # @return [Boolean] `false`
+ # @return [Boolean] `true` only if the node does not have a parent
def root?
- false
+ !parent
end
# Flag for terminal nodes.
# @return [Boolean] `true` for terminal nodes, `false` otherwise.
def terminal?
!!terminal
end
+ # Force [Node] to be `terminal`
+ # @return [Node] the modified node.
+ def terminal!
+ self.terminal = true
+ self
+ end
+
# String representation of the current node.
# @return [String] the string representation of the current node.
def to_s
parent.to_s << letter.to_s
end
- protected
-
- attr_writer :children_tree
- attr_accessor :terminal
-
def letter= new_letter
if new_letter
@letter = new_letter.to_sym
parent[letter] = self if parent
end
end
+
+ private
+
+ attr_accessor :terminal
end
end
end