From: Mark Wilson Date: 2003-10-01T11:16:20+09:00 Subject: Re: Making == symmetric? Those more knowledgeable than me should correct what I've written below if it's wrong. On Tuesday, September 30, 2003, at 07:19 PM, Nathan Weston wrote: > It has always bothered me that == is not symmetric in ruby: > a == b is shorthand for a.==(b), while b == a is shorthand for > b.==(a), and a and b might not agree on whether they are equal. I think it is symmetric so long as you bear in mind that the method belongs to the object and not to the variable that refers to the object. See below. > [snip] > First of all: yes, this issue does come up in real code. > Here's a quick example I ran into today: > > require "delegate" > class Foo > end > class D < SimpleDelegator > def initialize(obj) > super(obj) > end > end > f = Foo.new > d = D.new(f) > d == f #evaluates to true > f == d #evaluates to false I think you're mixing up variables and values. d refers to a D object instantiated with a Foo object. f refers to the Foo object used to instantiate the D object. The D object has an == method that checks its value and compares it to the given value. When invoked by d==f, the D object sees that its value is the Foo object and sees that f refers to the Foo object and determines that they are the same object. In other words the D object is the functional equivalent of an assignment to a primitive variable. The Foo object does not have a value other than its object id (I think). When it queries the value of the variable d in performing the == method, it gets the object id of the D object (I think). The two are not equal. The proper comparison would be: f.inspect==d.inspect Another way of looking at it: D.new(Foo.new) == Foo.new # false Foo.new == D.new(Foo.new) # false > I ran into a similar problem trying to implement perl6-style > junctions: you end up with any(1,2,3) == 1 being true, but 1 == > any(1,2,3) being false. I didn't follow the above point. There was an earlier discussion on the list about perl6-style junctions that might be helpful. > [snip] Regards, Mark