Skip to content

Instantly share code, notes, and snippets.

@padde
Created January 26, 2013 17:59
Show Gist options
  • Save padde/4643528 to your computer and use it in GitHub Desktop.
Save padde/4643528 to your computer and use it in GitHub Desktop.
Hacky completion class in Ruby. Useful for automatically abbreviating commands etc.
require 'fuzzy_match'
require 'amatch'
require 'text'
class Completion
attr_accessor :keywords
def initialize( keywords=[] )
self.keywords = keywords.map(&:downcase)
ambiguous = true
end
def find( s )
s = s.downcase
find_partial(s).first ||
find_fuzzy(s).first ||
find_levenshtein(s).first
end
# find by partial matching, taken from goruby
def find_partial( s )
regexp = Regexp.new "^#{ s.gsub(/./){ '(.*?)' + Regexp.escape($&) } }"
keywords.grep(regexp).sort_by do |x|
x.match(regexp).captures.map(&:size) << x
end
end
# find string with FuzzyMatch
def find_fuzzy( s )
FuzzyMatch.new(keywords).find_all(s)
end
# find by levenshtein distance
def find_levenshtein( s )
keywords.sort_by do |x|
Text::Levenshtein::distance(s, x)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment