At Thu, 29 Nov 2001 14:05:00 +0900,
Rich Kilmer <rich / infoether.com> wrote:
> excellent idea...how about this refactoring...

I thought up another trick.

class Signature < Array
  def invalid
    TypeError.new("Invalid Signature: #{collect {|a| a.type}.join(', ')}")
  end

  def ===(args)
    length == args.length or return false
    each_with_index {|t, i| t === args[i] or return false}
    true
  end
end

if __FILE__ == $0
  class Fred
    def hello(*args)
      case args = Signature[*args]
      when Signature[Fixnum, String, Float]
	i, s, f = args
	puts "(Fixnum, String, Float) -> [ #{i}, \"#{s}\", #{f} ]"
	"1"
      when Signature[String, Fixnum]
	s, i = args
	puts "(String, Fixnum) -> [ \"#{s}\", #{i} ]"
	return "2"
      else
	raise args.invalid
      end
    end
  end

  f = Fred.new
  f1 = f.hello(123, "hello", 123.456)
  f2 = f.hello("hello", 123)
  f3 = (f.hello("abc", "def") rescue $!)

  puts "f1 = #{f1.inspect}  f2 = #{f2.inspect}  f3 = #{f3.inspect}"
end

Nobu Nakada