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