Class: Matchers::Trie

Inherits:
Object
  • Object
show all
Defined in:
lib/matcher.rb

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(patterns) ⇒ Trie

Returns a new instance of Trie.



71
72
73
74
75
76
77
# File 'lib/matcher.rb', line 71

def initialize(patterns)
  @root = Node.new
  @root.children.default = @root
  patterns.each do |pattern|
    insert(pattern)
  end
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



69
70
71
# File 'lib/matcher.rb', line 69

def root
  @root
end

Instance Method Details

#forward_match(pattern) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/matcher.rb', line 86

def forward_match(pattern)
  return false if @root.children.empty?

  cur_node = @root
  pattern.chars.each do |char|
    return true if cur_node.children.empty?
    return false unless cur_node.children.key?(char)

    cur_node = cur_node.children[char]
  end
  true
end

#insert(pattern = '') ⇒ Object



79
80
81
82
83
84
# File 'lib/matcher.rb', line 79

def insert(pattern = '')
  current_node = @root
  pattern.chars.each do |char|
    current_node = current_node.insert(char)
  end
end