Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module AutoCall
def method_missing(method, *args)
__send__(find_nearest_method(method), *args)
end
private
def find_nearest_method(method)
methods.sort_by{ |my_method|
levenshtein_distance(my_method, method)
}.first
end
# http://d.hatena.ne.jp/kenkitii/20090204/ruby_levenshtein_distance
def levenshtein_distance(str1, str2)
col, row = str1.size + 1, str2.size + 1
d = row.times.inject([]){|a, i| a << [0] * col }
col.times {|i| d[0][i] = i }
row.times {|i| d[i][0] = i }
str1.size.times do |i1|
str2.size.times do |i2|
cost = str1[i1] == str2[i2] ? 0 : 1
x, y = i1 + 1, i2 + 1
d[y][x] = [d[y][x-1]+1, d[y-1][x]+1, d[y-1][x-1]+cost].min
end
end
d[str2.size][str1.size]
end
end
list = [1,2,3,4]
list.instance_eval{
extend AutoCall
}
puts list.lengtththhth # => 4
p list.revvvvvvvvvvvvvvverse # => [4, 3, 2, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment