Module: Philiprehberger::FuzzyMatch
- Defined in:
- lib/philiprehberger/fuzzy_match.rb,
lib/philiprehberger/fuzzy_match/dice.rb,
lib/philiprehberger/fuzzy_match/version.rb,
lib/philiprehberger/fuzzy_match/levenshtein.rb,
lib/philiprehberger/fuzzy_match/jaro_winkler.rb
Defined Under Namespace
Modules: Dice, JaroWinkler, Levenshtein
Constant Summary
collapse
- VERSION =
'0.1.6'
Class Method Summary
collapse
-
.best(query, candidates, threshold: 0.0) ⇒ Object
-
.dice_coefficient(str_a, str_b) ⇒ Object
-
.jaro_winkler(str_a, str_b) ⇒ Object
-
.levenshtein(str_a, str_b) ⇒ Object
-
.ratio(str_a, str_b) ⇒ Object
-
.search(query, candidates, threshold: 0.3) ⇒ Object
-
.suggest(query, candidates, threshold: 0.6, max: 5) ⇒ Object
Class Method Details
.best(query, candidates, threshold: 0.0) ⇒ Object
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/philiprehberger/fuzzy_match.rb', line 32
def self.best(query, candidates, threshold: 0.0)
return nil if candidates.empty?
best_result = nil
best_score = -1.0
candidates.each do |candidate|
score = ratio(query, candidate.to_s)
if score > best_score
best_result = candidate
best_score = score
end
end
return nil if best_score < threshold
{ match: best_result, score: best_score.round(4) }
end
|
.dice_coefficient(str_a, str_b) ⇒ Object
18
19
20
|
# File 'lib/philiprehberger/fuzzy_match.rb', line 18
def self.dice_coefficient(str_a, str_b)
Dice.coefficient(str_a, str_b)
end
|
.jaro_winkler(str_a, str_b) ⇒ Object
14
15
16
|
# File 'lib/philiprehberger/fuzzy_match.rb', line 14
def self.jaro_winkler(str_a, str_b)
JaroWinkler.similarity(str_a, str_b)
end
|
.levenshtein(str_a, str_b) ⇒ Object
10
11
12
|
# File 'lib/philiprehberger/fuzzy_match.rb', line 10
def self.levenshtein(str_a, str_b)
Levenshtein.distance(str_a, str_b)
end
|
.ratio(str_a, str_b) ⇒ Object
22
23
24
25
26
27
28
29
30
|
# File 'lib/philiprehberger/fuzzy_match.rb', line 22
def self.ratio(str_a, str_b)
a = str_a.to_s.downcase
b = str_b.to_s.downcase
max_len = [a.length, b.length].max
return 1.0 if max_len.zero?
distance = Levenshtein.distance(a, b)
1.0 - (distance.to_f / max_len)
end
|
.search(query, candidates, threshold: 0.3) ⇒ Object
51
52
53
54
55
56
57
58
59
|
# File 'lib/philiprehberger/fuzzy_match.rb', line 51
def self.search(query, candidates, threshold: 0.3)
scored = candidates.map do |candidate|
score = ratio(query, candidate.to_s)
{ match: candidate, score: score.round(4) }
end
results = scored.select { |r| r[:score] >= threshold }
results.sort_by { |r| -r[:score] }
end
|
.suggest(query, candidates, threshold: 0.6, max: 5) ⇒ Object
61
62
63
64
|
# File 'lib/philiprehberger/fuzzy_match.rb', line 61
def self.suggest(query, candidates, threshold: 0.6, max: 5)
results = search(query, candidates, threshold: threshold)
results.first(max).map { |r| r[:match] }
end
|