Skip to content
This repository has been archived by the owner on Oct 27, 2020. It is now read-only.
aurelian edited this page Sep 13, 2010 · 7 revisions

Ruby-AhoCorasick API

require 'ahocorasick'

Classes defined inside AhoCorasick modules:

KeywordTree

Class Methods

  • initialize creates a new and empty KeywordTree
tree = AhoCorasick::KeywordTree.new # => #<AhoCorasick::KeywordTree:0x762474>
  • from_file(file_name) creates a new KeywordTree and loads each line from file_name into the tree
tree= AhoCorasick::KeywordTree.from_file('dictionary.txt') # => #<AhoCorasick::KeywordTree:0x921381>

Instance Methods

  • add_string(string, [int id]) adds a new item to the tree, if the id is nil this method will generate one, otherwise will use the one that has been provided. Returns the id.
tree.add_string("string") => 1
tree.add_string("other string", 5) => 5
tree << "another one" # => 6
  • size gets the size of the tree
tree.size # => 3
  • make freeze the tree, an Error will be raised if a new entry is added afterwards. A new search will unlock the tree.
>> tree.add_string "foo"
=> 1
>> tree.make
=> true
>> tree.add_string "bar"
RuntimeError: Cannot add `bar" into a frozen tree.
        from (irb):7:in `add_string'
        from (irb):7
>> tree.find_all "foo"
=> [{:value=>"foo", :ends_at=>3, :starts_at=>0, :id=>1}]
>> tree.add_string "bar"
=> 2
  • find_all(string) does the search
results= tree.find_all("another one bites the dust") # => Array
results.each do | result |
  puts result[:starts_at] # => 0 
  puts result[:ends_at]  # => 11
  puts result[:value] # => "another one"
  puts result[:id] # => 6 
end
  • filter returns the attached ResultFilter.
  • filter= sets a new ResultFilter

ResultFilter

This class expose only an interface for one to define his own filter, see ResultFilter for details.

Clone this wiki locally