From: Ron Jeffries Date: 2001-08-14T21:09:50+09:00 Subject: [ruby-talk:19689] Re: Why not?: Assigning to self On 13 Aug 2001 20:59:54 -0700, furufuru@ccsr.u-tokyo.ac.jp (Ryo Furue) wrote: >Now the "why" part of the question remains. I'm curious about why an >assignment to self is forbidden. Is it to avoid surprises? or is it >related to some technical problem? As matz points out, assignment means reference. So we might have a = X.new b = a c = b which winds up with three variables all pointing to the same object. If we then do self = Something.new _all_ those variables have to be pointing to something new. There are ways to do that. Matz refers to Smalltalk #become: which is typically implemented by searching out all references to the old object and replacing them with the new. This is costly in the extreme. It is also possible, sometimes, to replace the original real object with some kind of a forwarder to the new. This amortizes the cost, but is still costly. One could even build a language where there was one more level of indirection in between the reference and the real object. Then an assignement to self could just change that master pointer. I don't know if anyone has ever built a language that way. Probably the benefit doesn't outweight the cost in the minds of the designers. When we need to do something that feels like assigning to self, there are patterns for pluggable behavior that make the code more clear. We're probably looking for something like Strategy. That's where I'd go. Regards, Ronald E Jeffries http://www.XProgramming.com http://www.objectmentor.com