Class: RegexpTrie

Inherits:
Object
  • Object
show all
Defined in:
lib/regexp_trie.rb,
lib/regexp_trie/version.rb

Constant Summary collapse

VERSION =
"1.0.3"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*strings) ⇒ RegexpTrie

Returns a new instance of RegexpTrie.



16
17
18
19
20
21
22
# File 'lib/regexp_trie.rb', line 16

def initialize(*strings)
  @head = {}

  strings.flatten.each do |str|
    add(str)
  end
end

Class Method Details

.union(*strings, option: nil) ⇒ Regexp

Factly method to call ‘new(*strings).to_regexp(option)` in short.

Parameters:

  • strings (Array<String>)

    Set of patterns

  • option (Integer, Boolean) (defaults to: nil)

    The second argument of ‘Regexp.new()` passed to build a regexp instance

Returns:

  • (Regexp)


12
13
14
# File 'lib/regexp_trie.rb', line 12

def self.union(*strings, option: nil)
  new(*strings).to_regexp(option)
end

Instance Method Details

#add(str) ⇒ Object

Parameters:

  • str (String)


25
26
27
28
29
30
31
32
33
34
35
# File 'lib/regexp_trie.rb', line 25

def add(str)
  return self if !str || str.empty?

  entry = @head
  str.each_char do |c|
    entry[c] ||= {}
    entry = entry[c]
  end
  entry[:end] = nil
  self
end

#to_regexp(option = nil) ⇒ Regexp

Returns:

  • (Regexp)


47
48
49
# File 'lib/regexp_trie.rb', line 47

def to_regexp(option = nil)
  Regexp.new(to_source, option)
end

#to_sourceString

Returns:

  • (String)


38
39
40
41
42
43
44
# File 'lib/regexp_trie.rb', line 38

def to_source
  if @head.empty?
    Regexp.union.source
  else
    build(@head)
  end
end