From: "Benjamin J. Tilly" Date: 2001-03-23T13:22:59+09:00 Subject: [ruby-talk:13113] Re: alias method >===== Original Message From "Nathaniel Talbott" ===== >Kenichi Komiya [mailto:kom@mail1.accsnet.ne.jp] wrote: [...] >Ah, I see. If we think of the class as just holding a reference to a method >instance, alias_method is just adding a new method reference to the class >and pointing it at the same method instance as the original reference. >Changing what the original reference points at obviously doesn't change what >the new reference points at. Now that I understand that, the current >behavior makes sense, but it certainly doesn't seem obvious at first blush. >Dave & Andy, do you think it would be valuable to clarify this in the book? Ruby generally works this way. When you copy a variable, copies by default are shallow. But modification creates a new instance so this usually works out as you would expect. >It still seems that, whatever it's doing underneath, from a usage standpoint >the current alias_method() is copying the method, since I don't think >there's a way to change the original method such that it affects the >'alias'. Is this true? [...] I don't know how to do it off of the top of my head with methods, but the following example with arrays may be enlightening: a = [1, 2, 3, 4, 5] p "a", a b = a p "b", b a.push(6) p b a = a + [7] p b p a You see that when you copied a to b, you get an alias. If you modify a in place (eg with push()) you will modify b as well. But attempt a common operation (eg +) on a, and a new object is created which protects b from seeing the change. Therefore while copying usually copies by reference, in practice you see few surprises. (Though they certainly exist.) Cheers, Ben