End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Gem::Text#levenshtein_distance
levenshtein_distance(str1, str2)
lib/rubygems/text.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.0.5/lib/rubygems/text.rb, line 54
def levenshtein_distance(str1, str2)
s = str1
t = str2
n = s.length
m = t.length
return m if (0 == n)
return n if (0 == m)
d = (0..m).to_a
x = nil
str1.each_char.each_with_index do |char1,i|
e = i + 1
str2.each_char.each_with_index do |char2,j|
cost = (char1 == char2) ? 0 : 1
x = min3(
d[j + 1] + 1, # insertion
e + 1, # deletion
d[j] + cost # substitution
)
d[j] = e
e = x
end
d[m] = x
end
return x
end
This code is based directly on the Text gem implementation Returns a value representing the “cost” of transforming str1 into str2