Class: Manywords::DictionaryNode
- Inherits:
-
Object
- Object
- Manywords::DictionaryNode
- Defined in:
- lib/manywords/dictionary_node.rb
Instance Attribute Summary collapse
-
#count ⇒ Object
readonly
Returns the value of attribute count.
Instance Method Summary collapse
- #add_word(word, idx = 0) ⇒ Object
- #find_word(word, idx = 0) ⇒ Object
-
#initialize ⇒ DictionaryNode
constructor
A new instance of DictionaryNode.
Constructor Details
#initialize ⇒ DictionaryNode
Returns a new instance of DictionaryNode.
7 8 9 10 11 |
# File 'lib/manywords/dictionary_node.rb', line 7 def initialize @count = 0; @letters = {} @word = false end |
Instance Attribute Details
#count ⇒ Object (readonly)
Returns the value of attribute count.
5 6 7 |
# File 'lib/manywords/dictionary_node.rb', line 5 def count @count end |
Instance Method Details
#add_word(word, idx = 0) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/manywords/dictionary_node.rb', line 13 def add_word(word, idx = 0) # If we've reached the end of the word, mark it as so if idx == word.length @word = true return end # A word will be added, so increment @count += 1 # Get the letter and add it to the tree if we need to letter = word[idx] @letters[letter] = DictionaryNode.new unless @letters.key?(letter) # Go to the next letter @letters[letter].add_word word, idx + 1 end |
#find_word(word, idx = 0) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/manywords/dictionary_node.rb', line 31 def find_word(word, idx = 0) if !word.is_a?(String) && !word.is_a?(Array) raise "find_word requires an Array or a String" end # We've reached the end, so this is either a word or a partial word if idx == word.length return @word ? :yes : :maybe end # Check if this letter is valid letter = word[idx] if @letters.key? letter # Valid, so go to the next letter @letters[letter].find_word word, idx + 1 else :no end end |