From: Robert Klemme Date: 2004-02-26T21:34:48+09:00 Subject: Re: Operators +, += and = in Ruby 2 "Dennis Ranke" schrieb im Newsbeitrag news:opr3y7ryzv4wwk8i@News.CIS.DFN.DE... > On Thu, 26 Feb 2004 12:24:13 +0100, Robert Klemme wrote: > > > I didn't overlook that one. It was in the first post already: > > > > > > On the downside: > > [...] > > - dup might or might not be the appropriate method to create a copy > > depending on the class at hand. When defining operator +, we are > > currently > > free in deciding what's the type of result of this operation. That > > freedom would definitely go away. > > > > > > A solution would be to provide another method (maybe #copy or #op_dup or > > similar) that defaults to #dup but can be overridden to get another > > return > > value. > > Ok, but I can't really see this working. Let's take a Vector class, for > example, that defines the following operations: > > Vector = Vector + Vector (adding two vectors) > Float = Vector * Vector (calculating the dot product) > Vector = Vector * Float (scaling a vector) > > Now the resulting type depends on both the actual Op used as well as the > type of the second operand. While it would certainly be possible to call > #op_dup with all of this information, it sounds quite ulgy to have one > method that has to know about the inner workings of all the operators. Yep, true. I didn't think of multiple dispatch but you're right that this is ugly. One could solve that by defining #op_dup this way: def op_dup(op_sym, op_obj) dup end That would allow overriding implementations to decide which return value to create. > Another problem (which is much harder to solve) is: What kind of object > should receive the *= message in the case of the "Float = Vector * Vector" > operation? Clearly the result of #op_dup. First a copy is created and then the inplace operation is performed. > A Vector that turns into a Float while processing the message? > I can't say that I like the sound of objects changing their class in this > way. No instance changes its class here. > > That would lead into the directon of C++ where you can overload all these > > operators independently. Dunno whether that is a good idea or not, but I > > always liked the idea that there was only one set of operators I needed > > to > > define and got the rest for free. We could maintain this by defining #+, > > #- etc. in Object using #+= etc. internally. So we would retain the > > automatism while not reducing freedom too much. > > I think the closest you could ever get to this would be the current ruby > way (ie. defining #+= using #+) and optionally being able to define your > own #+= as well. .... or the other way round, i.e. defining #+ using #+= and optionally defining #+ as well. Thanks for the feedback! Regards robert