From: "Darryl L. Pierce" Date: 2011-10-04T22:15:57+09:00 Subject: Re: Operator Overloading On 10/04/2011 01:11 AM, Thescholar Thescholar wrote: > Let's suppose I have a class like this one and then I create two > objects: > > =-=-=-=-=-=-=-=-=-=-=-= > class Point > > def initialize > x = 5 > y = 10 > z = 25 > end This won't work since x, y and z in the above are local to the constructor. So those variables will be lost when the constructor exits. > > end > > a = Point.new > b = Point.new > =-=-=-=-=-=-=-=-=-=-=-= > > How do I do if I want to add a and b together to a new point called c? > Example: > > c = a + b > > How exactly should I implement the operator overloading feature? So that > x = 10, y = 20, z = 50. There are hardly any tutorial for this... Define a + method on your Point class: def +(other) self.x += other.x self.y += other.y self.z += other.z self end That last line is IMPORTANT. Remember, Ruby methods treat the last value evaluated in a method as the return value. So if you don't put self in then the return value for the + method will be the last addition. So now with the above: c = a + b is the equivalent of doing: c = a.+(b) HTH. -- Darryl L. Pierce http://mcpierce.multiply.com/ "What do you care what people think, Mr. Feynman?"