Method Auto Completion (#112)


by Robert D.

First of all I would like to thank all submitters.

One of the best features of the Ruby Q. is it tolerance brings up new
ideas so

In order to honor this feature I will first present Daniel F.'s
solution. It
just abbreviates all defined methods. This very useful a feature which I
demonstrate after discussion of the code.

class Object
   def method_missing(method, *args, &blk)
      # Gather all possible methods it could be.
      possibleMethods = {|x|
x =~ /^#{Regexp.escape(method.to_s)}/
      case possibleMethods.size
      # No matching method.
      when 0
"undefined method `#{method}’ for " +
      # One matching method, call it.
      when 1
         method = possibleMethods.first
         send(method, *args, &blk)
      # Multiple possibilities, return an array of the
         "Ambigous abbreviation #{method} -> " +
“#{ possibleMethods.join(”, “)}”

Nothing very complicated there, just define method_missing in Object as
a catch
all for undefined methods in any object. Than he creates an array of all
which are legal completions of a potential abbreviation. In case there
are none
an original NoMethodError is mimicked. In case there is exactly one it
executed via send, please note the (method, *args, &blk) syntax, the
&blk part
has been forgotten in some solutions but is vital in #method_missing.
eventually if there are more Daniel returned an array of all completions
testing. I will discuss this later.

I have adapted this to return a message explaining what completions
exist for
the abbreviation. Why? Well I just fired up my irb and requested
solution, see what I got, much less typing for free. Here are some
excerpts of
my irb session.

irb(main):001:0> require ‘sol2’
=> true
irb(main):002:0> “a”.le
=> 1
irb(main):003:0> “abba”.le
=> 4
irb(main):004:0> “Hello World”.spl
=> [“Hello”, “World”]
irb(main):005:0> “Hi there Daniel”.sp
=> [“Hi”, “there”, “Daniel”]
irb(main):006:0> “Hi there Daniel”.s
=> “Ambigous abbreviation s ->Â select, slice, sub!, squeeze, send,
size, strip, succ!, squeeze!, sub, slice!, scan, sort, swapcase,
sum, singleton_methods, succ, sort_by, strip!”
irb(main):007:0> 12.x
NoMethodError: undefined method x' for 12:Fixnum             from ./sol2.rb:9:inmethod_missing’
            from (irb):7

Quite nice as a side product, no?

Let us turn towards solutions which respected the idea of defining
abbreviations, being interpreted in Command Line Interfaces for example.
It was
extremely difficult to chose a solution because most of the solutions
had their
strong parts. I eventually decided to comment on Donald B.'s solution
as it
was maybe the most readable solution for myself. I had discussed this
with James
who favored other solutions for other reasons and I will mention these
shortly. As always there is something in every solution so take your
time and
read them.

Ok here is Donald’s code - slightly modified again.

require ‘set’

module AutoComplete
   module ClassMethods
      attr_reader :abbrs
      def abbrev(*args)
         # TODO abbrs might be better implemented as a sorted set
         @abbrs ||=
         @abbrs += args
   module ObjectMethods
      def method_missing(id, *args, &blk)
         # if it is an exact match, there is no corresponding
# or else it would have been called
         if self.class.abbrs.include?(id)
         s = id.to_s
         len = s.length
         # find all abbreviations which begin with id and have
# active methods
         matches = { |abbr|
abbr.to_s[0,len] == s && respond_to?(abbr)
         if matches.length == 0
         elsif matches.length == 1
            send(matches[0], *args, &blk)

class Object
   extend AutoComplete::ClassMethods
   include AutoComplete::ObjectMethods

Although this can be done more concisely I eventually started to like
explicit way.

Lots of little details can be changed and they were in other solutions.
everybody wanted a NoMethodError thrown in case an abbreviation target
was an
abbreviation of a different method and was not there.

Ken B. was the first to point out that it was a bad idea to return an
of abbreviations in case of ambiguities. I completely agree, that was
only for
the test code anyway.

A great majority of the solutions follow this idea which is certainly a
under some circumstances. I imagine a DSL which is not interactive and
where the
interpreter has no choice than to throw an Exception, good thinking

Ken’s solution has three features noteworthy, first he added the list of
possible completions as an attribute of the exception he throws,
secondly he
just used the abbrev Standard Library Module and thirdly he used #super
#method_missing to raise a NoMethodError. super in that case calls
Kernel#method_missing. This took me some time to figure out. I guess the
road to
Ruby mastery is not answering quizzes but submitting quizzes and
the solutions. But you will find some of these features in other
solutions too.

Let us finish the summary with his code, another astonishing example of
how much
can be done with so little code in Ruby.

require ‘abbrev’

class AmbiguousExpansionError < StandardError
attr_accessor :candidates
def initialize(name,possible_methods)
super(“Ambiguous abbreviaton: #{name}\n”+
“Candidates: #{possible_methods.join(”, “)}”)

module Abbreviator
def method_missing name,*args
return send(abbrevs[name.to_s],*args) if abbrevs[name.to_s]
meths=abbrevs.reject{|key,value| key!~/^#{name}/}.values.uniq
raise, meths) if meths.length>1
return super(name,*args)

Many thanx to everyone…


For those keeping score at home, this message had a bad subject. It
was the summary to quiz 110, not 112. I fat-fingered the launch. My

James Edward G. II