Module: Philiprehberger::FuzzyMatch::Dice

Defined in:
lib/philiprehberger/fuzzy_match/dice.rb

Class Method Summary collapse

Class Method Details

.coefficient(str_a, str_b) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/philiprehberger/fuzzy_match/dice.rb', line 6

def self.coefficient(str_a, str_b)
  a = str_a.to_s.downcase
  b = str_b.to_s.downcase

  return 1.0 if a == b
  return 0.0 if a.length < 2 || b.length < 2

  bigrams_a = bigrams(a)
  bigrams_b = bigrams(b)

  intersection = 0
  b_copy = bigrams_b.dup

  bigrams_a.each do |bg|
    idx = b_copy.index(bg)
    if idx
      intersection += 1
      b_copy.delete_at(idx)
    end
  end

  (2.0 * intersection) / (bigrams_a.length + bigrams_b.length)
end