From: Rick DeNatale Date: 2008-04-10T05:07:21+09:00 Subject: Re: My error or bug in "attr_reader" ? On Wed, Apr 9, 2008 at 3:09 PM, Hexren wrote: > > Stefano Crocco wrote: > > > On Wednesday 09 April 2008, Hexren wrote: > > > > > Hi guys. > > > > > > The code posted below actually modifies the array in the object. > > > Am I doing something wrong here ? > > > If not, this should imho be included in the doc. It seems > > > counterintuitive to me ;) > > > > > > > > > Regards > > > Oliver > > > > > > ---------------------------------- > > > class AttrReaderErr > > > attr_reader :entries > > > def initialize() > > > @entries = [0,1,2] > > > end > > > end > > > > > > showcase = AttrReaderErr.new > > > > > > puts showcase.entries > > > #should this really work ? > > > showcase.entries[1]="foo" > > > #it does, but looks wrong > > > puts showcase.entries > > > ---------------------------------- > > > > > > > It works correctly, once you understand exactly what's going on. > attr_reader creates a method which returns the object stored in the instance > variable @entries. If it were written by hand, it would be something like: > > > > def entries > > @entries > > end > > > > Writing entries[1]="foo", you're calling the []= method of the object > returned by entries, that is, the array stored in @entries. Since the []= > method modifies the receiver, the content of @entries is modified. If you > don't want this to happen, you need to create the entries method by hand and > return a copy of the array: > > > > def entries > > @entries.dup > > end > > > > I hope this helps > > > > Stefano > > > > > > > Yup, what you say makes sense, thanks :) > > But I maintain, that the doc is kind of confusing. The fingerprint: > "attr(symbol, writable=false) => nil" > > Very strongly implies (at least to me) that the default is, for the > instance variable to be not writable. I am going to go, cry wolf on the doc > mailing list :) This is a typical newbie confusion over instance variable vs. the objects they reference. http://talklikeaduck.denhaven2.com/articles/2006/09/13/on-variables-values-and-objects See in particular the section on "Mutability, and Aliasing" -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/