Created
March 20, 2013 20:56
-
-
Save emberlzhang/5208346 to your computer and use it in GitHub Desktop.
Need to install gem 'levenshtein-ffi'
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
require 'levenshtein' | |
def sorted_lev(word, werd_collection) | |
lev_result = fancy_lev(word, werd_collection) | |
lev_result.sort! do |a,b| | |
a[1] <=> b[1] | |
end | |
end | |
def fancy_lev(word, werd_collection) | |
lev_result = [] | |
werd_collection.each do |werd| | |
lev_result << [werd, basic_lev(word, werd)] | |
end | |
lev_result | |
end | |
def basic_lev(word1, word2) | |
Levenshtein.distance(word1, word2) | |
end |
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
require_relative 'levenshtein' | |
describe "basic_lev" do | |
it "should calculate the levenshtein distance between two words" do | |
basic_lev("hello", "hello").should eq 0 | |
basic_lev("hello", "hal").should eq 3 | |
basic_lev("hello", "randomness").should eq 9 | |
end | |
end | |
describe "fancy_lev" do | |
let(:collection) { ["hal", "hello", "randomness"] } | |
it "should calculate the levenshtein distance between a word and each word of collection" do | |
fancy_lev("hello", collection).should eq [["hal", 3], ["hello", 0], ["randomness", 9]] | |
end | |
end | |
describe "sorted_lev" do | |
let(:collection) { ["randomness", "hal", "hello"] } | |
it "should return the levenshtein distance between a word and each word of collection, in ascending order of distance" do | |
sorted_lev("hello", collection).should eq [["hello", 0], ["hal", 3], ["randomness", 9]] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment