Class: PrefixTree
- Inherits:
-
Object
- Object
- PrefixTree
- Defined in:
- lib/bad_word_detector/prefix_tree.rb
Instance Method Summary collapse
- #<<(string) ⇒ Object
- #==(sec) ⇒ Object
- #[](string = '') ⇒ Object
- #children?(string) ⇒ Boolean
- #clone ⇒ Object
- #hash_tree ⇒ Object
-
#initialize(items = [], hash_tree = {}) ⇒ PrefixTree
constructor
A new instance of PrefixTree.
- #inspect ⇒ Object
- #value ⇒ Object
Constructor Details
#initialize(items = [], hash_tree = {}) ⇒ PrefixTree
Returns a new instance of PrefixTree.
6 7 8 9 10 11 12 13 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 6 def initialize(items = [], hash_tree = {}) @hash_tree = hash_tree.clone unless items.empty? items.each do |i| self << i end end end |
Instance Method Details
#<<(string) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 19 def << (string) parts = string.chars new_hash = self.hash_tree parts.each do |part| unless new_hash[part] new_hash[part] = {} end new_hash = new_hash[part] end new_hash[:value] = string self end |
#==(sec) ⇒ Object
56 57 58 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 56 def == (sec) sec.hash_tree == self.hash_tree end |
#[](string = '') ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 32 def [] (string = '') parts = string.chars new_hash = self.hash_tree parts.each do |part| unless new_hash[part] return nil end new_hash = new_hash[part] end PrefixTree.new [], new_hash end |
#children?(string) ⇒ Boolean
48 49 50 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 48 def children? (string) (self[string].hash_tree.keys - [:values]).any? end |
#clone ⇒ Object
52 53 54 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 52 def clone PrefixTree.new [], self.hash_tree end |
#hash_tree ⇒ Object
15 16 17 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 15 def hash_tree @hash_tree end |
#inspect ⇒ Object
2 3 4 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 2 def inspect "#<#{self.class.name}:#{self.object_id}>" end |
#value ⇒ Object
44 45 46 |
# File 'lib/bad_word_detector/prefix_tree.rb', line 44 def value self.hash_tree[:value] end |