Stop thinking of =, ==, +, *, <=,.... as operators. Think of them as
methods.
Correct. Usually. As seen below, = sometimes is just an operator.
Others like ! are never methods. And some, like != and +=, are
translated into multiple operators/methods. E.g.
# equivalent comparisons, you can't override != directly
a != b
!(a == b)
!(a.==(b))
# equivalent method calls
foo.a += 1
foo.a = foo.a + 1
foo.a=(foo.a + 1)
foo.a=(foo.a.+(1))
# equivalent assignments
a += 1
a = a + 1
a = a.+(1)
So, when you see "a = b" that's really saying call the method "=" on the
object "a" passing as an argument "b". If you think of it that way then
when you see the below method it will make more sense.
def a= (b)
@a = b
end
Not quite correct.
The = is translated by the parser into a method call only if the left
hand side has an explicit receiver:
# equivalent method calls
foo.a = b
foo.a=(b)
foo.send(:"a=", b)
But if the left hand side has no explicit receiver, the = is simply an
assignment operator to a local (or instance, or class instance)
variable:
# direct assignments
a = 5
@a = 5
@@a = 5
So, "a + b" is really:
def a+ (b)
return a + b
end
Also not quite correct. a + b *is* always a method call, but the name
of the method is just "+". a is the receiver and b is the argument:
# equivalent method calls
a + b
a.+(b)
a.send(:"+", b)
Even with an explicit receiver on the left hand side, it's just a
matter of a method call on the *value* of the left hand side:
# equivalent method calls
foo.a + b
foo.a.+(b)
# *not* equivalent
foo.send(:"a+", b)
As an aside, I don't think there's any syntax that would work for
invoking a method named "a+" other than using a direct send.
Jacob Fugal
···
On 5/11/06, Philip Hallstrom <ruby@philip.pjkh.com> wrote: