Class: RubyTrie::Trie

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_trie.rb

Overview

Trie implements a Trie structure via an underlying implementation using Tree Trie has a single attribute (root) which is the root TrieNode

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTrie

create an empty Trie



107
108
109
# File 'lib/ruby_trie.rb', line 107

def initialize
   @root = TrieNode.new('')
end

Instance Attribute Details

#rootObject (readonly)

The Trie just holds the root node



104
105
106
# File 'lib/ruby_trie.rb', line 104

def root
  @root
end

Instance Method Details

#add(string, value = true) ⇒ Object

add a string with optional value to the Trie Note - will overwrite the value if the node already exists :call-seq: add(string, value) -> TrieContent



117
118
119
# File 'lib/ruby_trie.rb', line 117

def add(string, value=true)
   @root.add_node(string, value)
end

#children(string) ⇒ Object

get all the children of a given prefix including the prefix, if it exists itself :call-seq: children(string) -> Array



133
134
135
136
137
138
139
140
141
# File 'lib/ruby_trie.rb', line 133

def children(string)
   parent = @root.get_node(string)
   return nil unless parent
   
   parent.inject([]) do |a,n| 
      a << n.content.string if n.content
      a
   end
end

#children_content(string) ⇒ Object

get the content of all children of a given prefix including the prefix, if it exists itself :call-seq: children_content(string) -> Array



162
163
164
165
166
167
168
169
170
# File 'lib/ruby_trie.rb', line 162

def children_content(string)
   parent = @root.get_node(string)
   return nil unless parent
   
   parent.inject([]) do |a,n| 
      a << n.content.to_a if n.content
      a
   end
end

#children_with_values(string) ⇒ Object

get all the children of a given prefix with thier values (as a [key,value] pair) including the prefix, if it exists itself :call-seq: children_with_values(string) -> Array



148
149
150
151
152
153
154
155
156
# File 'lib/ruby_trie.rb', line 148

def children_with_values(string)
   parent = @root.get_node(string)
   return nil unless parent
   
   parent.inject([]) do |a,n| 
      a << [n.content.string, n.content.value] if n.content
      a
   end
end

#get(string) ⇒ Object

get the value at a node returns nil if the node does not exist :call-seq: get(string) -> Object



125
126
127
# File 'lib/ruby_trie.rb', line 125

def get(string)
   @root.get_node_value(string)
end