Last active
September 4, 2023 15:46
-
-
Save CarlosUvaSilva/537f2e2716c9dd66e58b299448228d9e to your computer and use it in GitHub Desktop.
Simple Trigram comparison for 2 strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Trigrams | |
def self.trigramify(str) | |
trigs = [] | |
str.chars.each_cons(3) { |v| trigs << v.join } | |
trigs | |
end | |
def self.match_ratio(str_1, str_2) | |
text1_trigs = trigramify(str_1) | |
text2_trigs = trigramify(str_2) | |
all_cnt = (text1_trigs | text2_trigs).size | |
same_cnt = (text1_trigs & text2_trigs).size | |
same_cnt.to_f / all_cnt | |
end | |
def self.compare(str_1, str_2, min_ratio = 0.4) | |
match_ratio(str_1, str_2) >= min_ratio | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment