From: Joel VanderWerf Date: 2002-09-12T05:37:28+09:00 Subject: Re: Multimethods (was Re: Larry Wall's comments on Ruby) Christoph wrote: > "Justin Johnson" wrote > .... > >>I'd be interested to see if anyone could come up with some satisfactory >>syntax with regards to implementing multi-dispatch in Ruby. > > > Well the following is commonly used (Matz does not like it > if I remember correctly) > > <(a,b)>.atan > > or if you declare new key words like pair,multi,sym or alt > you could write for example > > multi(a.b).atan(), pair(a,b).atan or multi(a,b,c).mth(d,e,*f) > > If you prefer a more conventional look how about > > a.atan(b;) or a.mth(b,c ; d , e, *f) ? Without changing Ruby internals, what about something like: module Physics Collide = GenericFunction.new {|actor, object, *args|} # # The generic function will dispatch on actor and object, but # simply pass args to the selected method. # # The distinction in the block can be detected by checking whether #arity # returns 3 or -3. # end class Ship < Actor # tell Physics how collisions involving ships work Physics::Collide.add_method Ship, Object do |ship, object, *args| ... end # a more specific method: Physics::Collide.add_method Ship, Ship do |ship, other_ship, *args| ... end end class Rock Physics::Collide.add_method Actor, Rock {|actor, rock, *args| ... } end