Skip to content

Instantly share code, notes, and snippets.

@sciolist
Created August 16, 2012 20:46
Show Gist options
  • Select an option

  • Save sciolist/3373516 to your computer and use it in GitHub Desktop.

Select an option

Save sciolist/3373516 to your computer and use it in GitHub Desktop.
Use some simple ngrams to figure out what method you wanted to call!
require './oh_god_why'
class Object
include FigureItOut
end
str = "hello, world."
puts str.make_upper_case # HELLO, WORLD.
this = "this be some text"
b = this.cannot("be").a_bad{|x|x.idea}
p b.to_a # ["be"]
module FigureItOut
def method_missing name, *args
return @@_base.call(name, *args) if @@running == 1
@@running = 1 #lets not go crazy, here..
begin
found_method = nearest_method name
unless found_method.nil? or found_method == :method_missing
return send(found_method, *args)
end
ensure
@@running = 0
end
@@_base.call(name, *args)
end
private
@@_base = Object.method(:method_missing)
@@running = 0
def add_grams sym, ht={}
m = sym.to_s
1.upto(m.size).each do |y|
0.upto(m.size-y-1).each do |x|
(ht[m[x..(x+y)]]||=[]).push sym
end
end
ht
end
def hit seek, haystack
weighted = seek.keys.map{|k|haystack[k]}.flatten.compact
.inject({}){|ht, n|ht[n]=(ht[n]||0)+1;ht}
.sort_by{|a|-a[1]}
return nil if weighted.nil?
return weighted[0][0]
end
def nearest_method name
ht = self.methods.inject({}){|ht, m|add_grams(m, ht)}
grams = add_grams(name.to_sym)
hit(grams, ht)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment