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