class RubyAnagrams::Node
A representation of a Node
in the trie data structure. @author Connor Lay
Attributes
Public Class Methods
Creates a new, non-terminal node with no children. @param symbol [Symbol, nil] the symbol the node represents. @param parent [Node, nil] the parent of the node. @return [Node] the node just created.
# File lib/anagrams/node.rb, line 16 def initialize symbol = nil, parent = nil @symbol = symbol @parent = parent @children = {} @terminal = false end
Public Instance Methods
Returns the child node associated with a symbol. @param symbol [Symbol] @return [Node] the child node associated with the symbol.
# File lib/anagrams/node.rb, line 34 def [] symbol @children[symbol] end
Adds a new child node representing a symbol to this node’s children. @param symbol [Symbol] the symbol the node represents. @param child [Node] the node to add as a child. @return [Node] the node just added.
# File lib/anagrams/node.rb, line 27 def []= symbol, child @children[symbol] = child end
# File lib/anagrams/node.rb, line 63 def inspect "<#{self.class}:#{self.object_id}, "\ "@symbol=#{@symbol ? ":#{@symbol}" : "nil"}, "\ "@word=#{terminal? ? word : "nil"}, "\ "@children=#{@children.each_key.to_a}>" end
Sets the node as a terminal.
# File lib/anagrams/node.rb, line 39 def terminal! @terminal = true end
Is the node a terminal? @return [Boolean] true if the node is a terminal, false otherwise
# File lib/anagrams/node.rb, line 45 def terminal? @terminal end
Returns the word the node represents based on its symbol and the symbols of its parents. @example called on the node representing :e
:a :p :p :l :e #word #=> "apple"
@return [String] the word the node represents.
# File lib/anagrams/node.rb, line 59 def word @parent ? "#{@parent.word}#{@symbol}" : "#{@symbol}" end