Class: Improvise::ForwardDictionary
- Inherits:
-
Dictionary
- Object
- Dictionary
- Improvise::ForwardDictionary
- Defined in:
- lib/improvise/forwarddictionary.rb
Instance Attribute Summary
Attributes inherited from Dictionary
Instance Method Summary collapse
- #generate_word(length, root = nil) ⇒ Object
-
#initialize(depth = 2, tree = nil) ⇒ ForwardDictionary
constructor
A new instance of ForwardDictionary.
- #learn!(words) ⇒ Object
Methods inherited from Dictionary
#as_json, json_create, #to_json
Constructor Details
#initialize(depth = 2, tree = nil) ⇒ ForwardDictionary
Returns a new instance of ForwardDictionary.
6 7 8 |
# File 'lib/improvise/forwarddictionary.rb', line 6 def initialize(depth=2, tree=nil) super(depth, tree) end |
Instance Method Details
#generate_word(length, root = nil) ⇒ Object
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/improvise/forwarddictionary.rb', line 10 def generate_word(length, root=nil) word = root || @tree.random_key while word.length < length do suffix = @tree.random_value(word[[-@depth, 0].max..-1]) word += suffix || @tree.random_key end Improvise::Util::StringUtils.truncate(word, length, omission: '') end |
#learn!(words) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/improvise/forwarddictionary.rb', line 21 def learn!(words) [*words].each do |word| start_of_word = word.slice(0..(@depth - 1)) @tree.add_entry!('', start_of_word) word.split('').each_cons(@depth + 1) do |characters| prefix = characters[0..-2].join('') suffix = characters[-1] @tree.add_entry!(prefix, suffix) end end end |