Class: Fuzzy

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

Class Method Summary collapse

Class Method Details

.find(strings, input) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/fuzzy_ruby.rb', line 3

def self.find(strings, input)
  # array to store weights of each string
  @weights = Array.new(strings.length, -1)

  # array to store each string
  @strings = strings.dup

  # array to return
  ret = Array.new

  # build regular expression
  regexp = /#{build_regexp(input)}/

  # for each string, calculate weight
  @strings.each_index do |i|
    assign_weights(i, regexp)
  end

  # delete string if there is no match
  @weights.each_index do |i|
    if @weights[i] == -1
      @weights.delete_at(i)
      strings.delete_at(i)
    end
  end

  # return array of strings with best match (least weight)
  @weights.map.with_index.sort_by(&:first).map(&:last).each do |index|
    ret.push strings[index]
  end

  return ret
end