From: Sam Roberts Date: 2003-02-10T04:04:18+09:00 Subject: Operator reordering, good idea? (was Re: ruby-dev summary 19457-19539) Hi, I'm just a beginner buy program, but... Quoteing ksaito@uranus.dti.ne.jp, on Mon, Feb 10, 2003 at 01:26:17AM +0900: > [ruby-dev:19457] equality between "a" and Exception.new("a") > > Akira Tanaka asked if it is intended that '==' doesn't have commutativity. I think anybody who has programmed with ruby for more than a few hours has to know that lhs == rhs is the same as: lhs.==(rhs) or they won't understand most things about the language. So, == is obviously not commutative. Neither is any other method. lhs.do_to rhs If lhs doesn't have a method "do_to", but rhs does, ruby could reorder this to rhs.do_to lhs but doesn't. > This behavior comes from the equality checking mechanism of String. > For example, the following two expressions doesn't return same value. > > (a) "a" == Exception.new("a") > (b) Exception.new("a") == "a" > > (a) returns true and (b) returns false. It is because Exception.new("a") > is automatically transformed to a String object "a" via to_str method in > case of (a). Matz changed a method for checking equality of strings as > follows. > > In case of a == b and b is not a String object, the expression is true > if b has a method to_str and b == a is true. If I understand this correctly, this is unpredictable and surprising to me. For me, one test of sensibility would be the question: how do I get this "commutative" behaviour for my own classes? Its easy to define a method "+" that converts its arg to some type if necessary, but how do I get ruby to reorder a "+" so that if my class is on the right, it gets put on the left? For example: irb(main):018:0> "a" + 5 TypeError: failed to convert Fixnum into String from (irb):18:in `+' from (irb):18 irb(main):019:0> class Fixnum irb(main):020:1> def to_str irb(main):021:2> self.to_s irb(main):022:2> end irb(main):023:1> end nil irb(main):024:0> "a" + 5 "a5" irb(main):025:0> 5 + "a" TypeError: String can't be coerced into Fixnum from (irb):25:in `+' from (irb):25 Will this change apply to String.+, or just String.==? Obviously, this is just my opinion. Thanks for such a fun language, Sam