-
-
Save jaydonnell/168068 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
module Edits | |
def deletes1 | |
map_transforms do |word, i| | |
word.delete_at(i) | |
end | |
end | |
def transposes | |
map_transforms do |word, i| | |
word[i], word[i+1] = word[i+1], word[i] | |
end | |
end | |
def replaces | |
("a".."z").map do |c| | |
map_transforms { |word, i| word[i] = c } | |
end.flatten | |
end | |
def inserts | |
("a".."z").map do |c| | |
map_transforms { |word, i| word.insert(i, c) } << "#{self}#{c}" | |
end.flatten | |
end | |
def map_transforms | |
out = [] | |
chars = self.split('') | |
self.size.times do |i| | |
yield(word = chars.dup, i) | |
word = word.join | |
out << word unless word == self | |
end | |
out | |
end | |
end | |
String.send(:include, Edits) | |
describe "a String, imbued with Edits" do | |
it "works" do | |
r = "crap".deletes1 | |
r.should == %w{ rap cap crp cra } | |
r = "crap".transposes | |
r.should == %w{ rcap carp crpa } | |
r = "crap".replaces | |
r.size.should == 25 * 4 | |
r.should include( "brap", "frap", "crep", "crop", "crad", "crak") | |
r = "crap".inserts | |
r.size.should == 26 * 5 | |
r.should include( "zcrap") | |
r.should include( "czrap") | |
r.should include( "crapz") | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment