class AhoCorasick
Constants
- VERSION
Public Class Methods
new(*args)
click to toggle source
# File lib/aho_corasick.rb, line 2 def initialize(*args) terms = terms_for(args) @root = TreeNode.new unsafe_insert(terms) create_suffix_links end
Public Instance Methods
insert(*args)
click to toggle source
# File lib/aho_corasick.rb, line 19 def insert(*args) terms = terms_for(args) unsafe_insert(terms) create_suffix_links end
match(string)
click to toggle source
# File lib/aho_corasick.rb, line 9 def match(string) matches = [] node = string.each_char.inject(@root) do |node, char| matches += node.matches if node (node && node.find(char.to_sym)) || @root.find(char.to_sym) end matches += node.matches if node return matches end
Private Instance Methods
create_suffix_links()
click to toggle source
# File lib/aho_corasick.rb, line 41 def create_suffix_links queue = @root.children.to_a.dup while !queue.empty? char, node = queue.shift node.suffix = node.parent == @root ? @root : (node.parent.suffix && node.parent.suffix.children[char.to_sym]) node.children.to_a.each do |entry| queue.push(entry) end end end
terms_for(args)
click to toggle source
# File lib/aho_corasick.rb, line 27 def terms_for(args) if args.length == 1 && args[0].is_a?(Array) args[0] else args end end
unsafe_insert(terms)
click to toggle source
# File lib/aho_corasick.rb, line 35 def unsafe_insert(terms) terms.each do |t| t.each_char.inject(@root) {|node, char| node.child_for(char.to_sym) }.add_match(t) end end