Skip to content

Instantly share code, notes, and snippets.

@pingles
Created June 23, 2009 10:15
Show Gist options
  • Save pingles/134468 to your computer and use it in GitHub Desktop.
Save pingles/134468 to your computer and use it in GitHub Desktop.
class String
def self.levenshtein(a, b)
case
when a.empty?: b.length
when b.empty?: a.length
else [(a[0] == b[0] ? 0 : 1) + levenshtein(a[1..-1], b[1..-1]),
1 + levenshtein(a[1..-1], b),
1 + levenshtein(a, b[1..-1])].min
end
end
def levenshtein(other)
self.class.levenshtein(self, other)
end
end
"Test".levenshtein("Test") # => 0
"Test".levenshtein("A Test") # => 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment