Created
May 29, 2014 20:14
-
-
Save schneems/a04e51d549cc0041c48b to your computer and use it in GitHub Desktop.
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 Levenshtein | |
def initialize(str) | |
@str = str.downcase | |
end | |
def distance(str2) | |
distances = (0..str2.length.next).to_a | |
@str.each_char.with_index do |char, i| | |
distances[0] = i + 1 | |
sub_cost = i | |
str2.downcase.each_char.with_index do |char2, j| | |
next_cost = distances[j + 1] | |
sub_cost += 1 unless char == char2 | |
distances[j+1] = [next_cost + 1, # insertion | |
distances[j] + 1, # deletion | |
sub_cost].min # sub | |
sub_cost = next_cost | |
end | |
end | |
distances[str2.length] | |
end | |
class Array | |
def initialize(array) | |
@array = array | |
end | |
def sort_by(str) | |
levenshtein = ::Levenshtein.new(str) | |
@array.sort_by! {|elem| levenshtein.distance(elem) } | |
end | |
end | |
end | |
lev = Levenshtein.new("migrato0n") | |
puts lev.distance("migration") | |
# => 2 | |
# useful for finding misspellings | |
array = Levenshtein::Array.new(%w{cat dog migration}) | |
array.sort_by("migrato0n").first | |
# => "migration" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The version in RubyGems is about 2x faster, but it isn't released yet. :'(
Result against released:
Against master:
Someday we'll have a RubyGems release!