From: "Jesús Gabriel y Galán" Date: 2013-01-17T02:25:08+09:00 Subject: Re: commutative operations On Wed, Jan 16, 2013 at 6:15 PM, Nokan Emiro wrote: > Hi there, > > How would you solve the issue below? I'm looking for an elegant > solution for this one. I usually bump into this when I create my own > types. > > I have a class that extends Ruby's standard type set with my own > type. This new type is something that is supposed to be able to > work together with the already existing, built-in classes as close as > possible. I mean it is a valid thing to for instance add a Fixnum > to it, multiply it by a Rational number (which isn't zero, of course), etc. > The class can do this, because it's :+, :*, :/, :- methods are > aware of these types. So, if x is an instance of my class, x + 1 works > fine, just like x * 2, and all the others. > > The problem is that while I write programs, I always think about + as > a commutative operation, so I unconsciously expect that not only > x + 1, but the expression 1 + x gives the same result, which is of > course not true, because 1 + x calls Fixnum#+, and that method > does not know anything about my class. > > How could I make at least Numeric classes behave this way? What > I want is that if a Numeric instance method receives an object as a > parameter that is an instance of my class, it should call the same > method on the argument with itself (I mean 'self') as the parameter > in case of commutative operatins, like + and *. The problem is a > bit more difficult in case of order-dependant operators, like / and -... > Take a look at this article: http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html specifically the part about type coercion and operator overloading. Jesus.