Skip to content

Instantly share code, notes, and snippets.

@CarlosUvaSilva
Last active September 4, 2023 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CarlosUvaSilva/537f2e2716c9dd66e58b299448228d9e to your computer and use it in GitHub Desktop.
Save CarlosUvaSilva/537f2e2716c9dd66e58b299448228d9e to your computer and use it in GitHub Desktop.
Simple Trigram comparison for 2 strings
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