From: Josh Cheek Date: 2011-10-04T14:26:24+09:00 Subject: Re: Operator Overloading --0016e64c145e5fd22b04ae725455 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Oct 4, 2011 at 12:11 AM, Thescholar Thescholar < thescholar@hotmail.ca> 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 > > 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... > > Thank you! > > -- > Posted via http://www.ruby-forum.com/. > > class Point attr_accessor :x, :y, :z def initialize(x=5, y=10, z=25) self.x = x self.y = y self.z = z end def +(point) Point.new x+point.x, y+point.y, z+point.z end def inspect "(#{x}, #{y}, #{z})" end end a = Point.new b = Point.new a # => (5, 10, 25) b # => (5, 10, 25) a + b # => (10, 20, 50) --0016e64c145e5fd22b04ae725455--