Adam Shelly
3/31/2008 6:38:00 PM
On 3/31/08, Adam Shelly <adam.shelly@gmail.com> wrote:
> On 3/31/08, Alex DeCaria <alex.decaria@millersville.edu> wrote:
> > I want to be able to multiply a NUMERIC object by my Foo object and have
> > it return a new Foo object with all the instance variables multiplied by
> > the Numeric object.
> [...]
> > I'm thinking I have to modify the "*" method for all the subclasses of
> > the NUMERIC class. Is this correct? Or am I missing something.
> >
> You don't need to modify Numeric, you just need to tell it how to
> coerce your object into a number.
>
Oops, I didn't read your message closely enough. Maybe Jason is
right, and you shouldn't even consider doing this, but something like
the following should work:
class Foo
attr_reader :x,:y
def initialize(x,y)
@x=x
@y=y
end
def coerce(n)
[Foo.new(n,n),self]
end
def +(other)
Foo.new(@x+other.x,@y+other.y)
end
def /(other)
Foo.new(@x/other.x,@y/other.y)
end
end
p (2 + Foo.new(3,0)) #=> #<Foo:0x27afcb8 @y=2, @x=5>
p f=Foo.new(4,10) #=> #<Foo:0x27afc68 @y=10, @x=4>
p 100/f #=> #<Foo:0x27afbdc @y=10, @x=25>