matz / ruby-lang.org (Yukihiro Matsumoto) wrote in message news:<997764002.547018.14264.nullmailer / ev.netlab.jp>... > Hi, Hi, Matz! > In message "[ruby-talk:19670] Re: Why not?: Assigning to self" > on 01/08/14, Ryo Furue <furufuru / ccsr.u-tokyo.ac.jp> writes: > > |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? I could imagine that if it were > |allowed, there could be lots of surprises; for example, > | > | class Array > | def meth > | s = "hello" > | self = s > | end > | end > | > | a = [3.14, 2.9] > | a.meth > | puts a # prints "hello" !! > | [...] > Assignments in Ruby is changing reference. There's no copy in > assignments. Thanks for pointing that out here! In fact I knew that, but my misunderstanding was that we could, within an instance method, make self refer to a different object, as if void meth(void*& self) { // reference to pointer void* s = new String("hello"); self = s; // self now points to a String object. } void* a = new Array(3.14, 2.9); meth(a); cout << *(String*)a << '\n'; // prints "hello". This much was my misunderstanding. I think the correct interpretation would be something like void meth(void* self) { // pointer void* s = new String("hello"); self = s; // self now points to a String object, but the effect // doesn't propagate to the caller. Would need to copy // the String object into the memory pointed to by self. } Cheers, Ryo