Class: Melisa::Trie

Inherits:
Object
  • Object
show all
Includes:
Enumerable, BaseConfigFlags
Defined in:
lib/melisa/trie.rb

Direct Known Subclasses

BytesTrie

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from BaseConfigFlags

#binary_flag, #config_flags, #lookup_cache_size, #valid_node_order, #valid_num_tries

Constructor Details

#initialize(keys = [], weights = [], opts = {}) ⇒ Trie

Initialize a BaseTrie.



20
21
22
23
24
25
26
27
# File 'lib/melisa/trie.rb', line 20

def initialize(keys=[], weights=[], opts={})
  @trie = Marisa::Trie.new
  @keyset = Marisa::Keyset.new
  @options = opts
  @built = false

  add_many(keys, weights)
end

Instance Attribute Details

#trieObject (readonly)

Returns the value of attribute trie.



10
11
12
# File 'lib/melisa/trie.rb', line 10

def trie
  @trie
end

Instance Method Details

#add(key, weight = nil) ⇒ Object Also known as: <<

Note: weight is not the same thing as a value! use a BytesTrie or IntTrie subclass if you want a key/value dictionary

Raises:



36
37
38
39
# File 'lib/melisa/trie.rb', line 36

def add(key, weight=nil)
  raise ImmutableError, "Can't add #{key}, Trie already built" if @built
  self.tap { push(key, weight) }
end

#add_many(keys, weights) ⇒ Object



42
43
44
45
46
# File 'lib/melisa/trie.rb', line 42

def add_many(keys, weights)
  for key, weight in keys.zip(weights)
    push(key, weight)
  end
end

#buildObject



29
30
31
32
# File 'lib/melisa/trie.rb', line 29

def build
  @trie.build(@keyset, config_flags(@options)) unless @built
  @built = true
end

#each(&block) ⇒ Object



53
54
55
56
# File 'lib/melisa/trie.rb', line 53

def each(&block)
  build unless @built
  search('').each(&block)
end

#has_keys?Boolean

Returns:

  • (Boolean)


68
69
70
71
# File 'lib/melisa/trie.rb', line 68

def has_keys?
  build unless @built
  search('').has_keys?
end

#include?(key) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
76
# File 'lib/melisa/trie.rb', line 73

def include?(key)
  build unless @built
  search('').include?(key)
end

#keysObject



63
64
65
66
# File 'lib/melisa/trie.rb', line 63

def keys
  build unless @built
  search('').keys
end

#load(path) ⇒ Object



78
79
80
# File 'lib/melisa/trie.rb', line 78

def load(path)
  self.tap { @trie.load(path); @built = true }
end

#save(path) ⇒ Object



82
83
84
85
# File 'lib/melisa/trie.rb', line 82

def save(path)
  build unless @built
  self.tap { @trie.save(path) }
end

#search(prefix) ⇒ Object



48
49
50
51
# File 'lib/melisa/trie.rb', line 48

def search(prefix)
  build unless @built
  Search.new(self, prefix)
end

#sizeObject



58
59
60
61
# File 'lib/melisa/trie.rb', line 58

def size
  build unless @built
  @trie.num_keys()
end