Class: Kaerukeyword::HashTree

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

Constant Summary collapse

END_TAG =
"en"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_array = []) ⇒ HashTree

Returns a new instance of HashTree.



185
186
187
188
# File 'lib/kaerukeyword.rb', line 185

def initialize(key_array = [])
  @nodes = {}
  make_tree(key_array)
end

Instance Attribute Details

#treeObject

Returns the value of attribute tree.



183
184
185
# File 'lib/kaerukeyword.rb', line 183

def tree
  @tree
end

Instance Method Details

#add(key) ⇒ Object

キーワードの追加



197
198
199
200
201
202
203
204
# File 'lib/kaerukeyword.rb', line 197

def add(key)
  cur = @nodes
  key.scan(/./).each do |c|
    cur[c] ||= {}
    cur = cur[c]
  end
  cur[END_TAG] = true
end

#make_tree(key_array) ⇒ Object



190
191
192
# File 'lib/kaerukeyword.rb', line 190

def make_tree(key_array)
  key_array.each{|key| add(key)}
end

#search(text) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/kaerukeyword.rb', line 206

def search(text)
  list = []
  word = ""
  buffer = ""
  cur = @nodes
  i = 0
  hit_i = nil
  str = text.scan(/./)

  loop do
    break unless c = str[i]

    unless cur.has_key?(c)
      if word.empty?
        i = (hit_i || i) + 1
      else
        list << word
        i = hit_i + word.scan(/./).size
        word = ""
      end
      hit_i = nil
      buffer = ""
      cur = @nodes
    end

    if cur.has_key?(c)
      cur = cur[c]
      buffer << c
      word = buffer.dup if cur.has_key?(END_TAG)
      hit_i = i unless hit_i
    end
    i += 1
  end

  list << word unless word.empty?
  list
end