Class: Fuzzy
- Inherits:
-
Object
- Object
- Fuzzy
- Defined in:
- lib/fuzzy_ruby.rb
Class Method Summary collapse
-
.assign_weights(index, regexp) ⇒ Object
recursive function to assign weight to string once there is match, removes one character from the reg exp and repeat.
-
.build_regexp(string) ⇒ Object
build the regular expression.
- .done(index) ⇒ Object
- .find(strings, input) ⇒ Object
Class Method Details
.assign_weights(index, regexp) ⇒ Object
recursive function to assign weight to string once there is match, removes one character from the reg exp and repeat
48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/fuzzy_ruby.rb', line 48 def self.assign_weights(index, regexp) weight = @strings[index] =~ regexp if weight == nil return end @weights[index] += weight if !done(index) @strings[index] = @strings[index][weight+1..@strings[index].length] assign_weights(index, /#{regexp.source[5..regexp.source.length]}/) end end |
.build_regexp(string) ⇒ Object
build the regular expression
38 39 40 41 42 43 44 |
# File 'lib/fuzzy_ruby.rb', line 38 def self.build_regexp(string) regexp = "" string.each_char do |c| regexp << "(\w*)#{c}" end regexp << "(\w*)" end |
.done(index) ⇒ Object
60 61 62 |
# File 'lib/fuzzy_ruby.rb', line 60 def self.done(index) @strings[index] == nil || @weights[index] == -1 ? true : false end |
.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 |