From: Jean-Hugues ROBERT Date: 2004-04-30T14:04:38+09:00 Subject: Re: coerce(), what protocol to implement it At 08:39 30/04/2004 +0900, you wrote: >Jean-Hugues ROBERT wrote: >.... >>Google "ruby coerce" provided little help. >>Thanks in advance, > >The coerce framework makes up for the lack of >multiple dispatch aka "method overloading", >whose lack can be a major nuisance when doing >numerical work. You probably should study the >source code of the standard libraries "complex" >or "rational, if you want to get a feel for >using this framework. Here is a scaled down >example > > >--- >class MyClass > > def initialize(val) > @value = val > end > > def coerce(other) > [MyClass.new(other),self] > end > > def -(lhs) > if MyClass === lhs > MyClass::new(@value - lhs.value) > else > x,y = lhs.coerce(@value) > MyClass::new(x - y) > end > end > > protected > attr_reader :value >end > >p 1 - MyClass.new(5) >p MyClass.new(5) - 1 > > >require 'complex' > >z = Complex(1.0,1) > >p z - MyClass.new(5) >p MyClass.new(5) - z >--- ># ># ># ># >--- >/Christoph Thanks a lot. Looking for some example code I had had a look at ruby/lib/ruby but there were so many files that I was slightly lost. Is there something like Class.implementers( meth) that would return a list of all known classes that implement some method ? It could not returned the classes that where never required but it may help understand the protocols for common methods that where designed to be redefined Additionally, is there something like a_class.sources() that would return an array of "positions" where source code for a a_class was "loaded". It would return something similar to what you get when an exception bombs at these positions. If so, then Class.implementers( :coerce).each do | klass | p "coerce() is implemented by #{klass}, maybe in:" p a_class.sources.join( "\n") end would list the files where there might be examples of how to implement the :coerce method. If I come up with a solution for this issue with Introspection, I will share it here. Thanks in advance, BTW: With all the help I received I am well on my way to implement a Reference class, like a Pointer but with some auto-dereferencing. OTOH maybe I should investigate a "proxy" type of solution, like the ones used by Drb or similar stuff. Yours, Jean-Hugues ------------------------------------------------------------------------- Web: http://hdl.handle.net/1030.37/1.1 Phone: +33 (0) 4 92 27 74 17