UMLETA.COM - software tools & development
software development and tools

Multimethod: Ruby Package for Multimethod Dispatching

Submitted by Kurt on November 21, 2006 - 4:15pm.

See: http://rubyforge.org/projects/multimethod/

The RubyForge package multimethod
implements multimethod dispatch of methods based on argument types.

require 'multimethod'

class A
  multimethod %q{
  def foo(x) # matches any argument type
     "#{x.inspect}"
  end
  }

  multimethod %q{
  def foo(Fixnum x) # matches any Fixnum
     "Fixnum #{x.inspect}"
  end
  }

  multimethod %q{
  def foo(Numeric x) # matches any Numeric
     "Numeric #{x.inspect}"
  end
  }
end

a = A.new
puts a.foo(:symbol) # ==> ":symbol"
puts a.foo(45)      # ==> "Fixnum 45"
puts a.foo(12.34)   # ==> "Numeric 12.34"

Variadic methods and default values are supported. It has a cleaner syntax than the multi package.

Install the gem:

gem install multimethod

For more examples, see:

I'd love to hear your feedback on this module.

-- Kurt

links: add new comment