Hexren wrote: > David A. Black wrote: >> 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. > > And that doesnt sound strange to you ? > I see why the stuff is writable in a technical sense. > > However that is not changing my opinion: Something called "attr_reader > :foo" should not allow somebody to write to "private @foo". > > And if it does make something writable it should say so in the api doc > and not hope that everybody catches that fact by glancing at the example > in the doc. > Which btw: is for the other case "writable=true". > > > Oliver > That somehow sounds harsher than I intended. No offense meant, its only my opinion. Oliver