From: Brian Candler Date: 2008-09-20T04:02:02+09:00 Subject: Re: why one array continues to grow after repeated call Randy Kramer wrote: > In C++, I could overload the = operator (I think) to do something > different than assignment However, you can't in Ruby. "x = y" cannot be made to mean anything other than "evaluate the expression 'y', and store the resulting reference in x" (*) > --if I did, I'd just confuse myself (at least > in most circumstances). In Ruby, somebody could make the []= method do > something other than assignment, but that would just be confusing (in > most circumstances), so I'd try to avoid it. Here's an example in the standard library of where []= is clearly not performing an assignment: irb(main):001:0> str = "abcdefgh" => "abcdefgh" irb(main):002:0> str["cde"]="x" => "x" irb(main):003:0> str => "abxfgh" You can see that here it's a string slicing operation, a mutation of the string. In any case, it's nothing to do with the assignment operator. Note that: x = y # *is not* a method call, and DOES NOT change ANY object (*) x[y] = z # *is* a method call, and CAN change object(s) I don't think I can put it any clearer than that. These really are completely different. Also, since "x = y" involves no method call, it's not possible to overload it or change its meaning in any way. Aside: the [] operator may *look* like looking up an element in an array, but it is very common for it to be used as something else. m = lambda { |x,y| x+y } puts m[3,4] # prints 7 HTH, Brian. (*) Note that 'y' could be a local variable, but it could be a method call. def y "hello" end x = y puts x y = 123 x = y puts x And therefore if it's a method call, invoking that method *could* modify objects as a side-effect. Whether a bare "y" is a method call or a local variable depends on a static, parse-time decision. If an *assignment* to a local variable y was parsed earlier in this scope, then it's a local variable. Note: "parsed" - not executed. So: def foo "hello" end if false foo = "goodbye" end puts foo # prints nil # But you can force the method call interpretation: puts self.foo puts foo() I mention this now because it hopefully it reinforces the need to recognise a true assignment, versus something which is actually a method call. -- Posted via http://www.ruby-forum.com/.