From: "David A. Black" Date: 2008-04-10T06:09:26+09:00 Subject: Re: My error or bug in "attr_reader" ? Hi -- On Thu, 10 Apr 2008, 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 :) A writable attribute is different from a mutable object. You can't set the attribute to a new object, but the read operation does expose the object behind the attribute -- so if that object is mutable, you can mutate it. David -- Rails training from David A. Black and Ruby Power and Light: ADVANCING WITH RAILS April 14-17 New York City INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin See http://www.rubypal.com for details and updates!