From: James French Date: 2009-11-07T01:01:36+09:00 Subject: Re: encapsulation issue > -----Original Message----- > From: Tom Stuart [mailto:tom@therye.org] > Sent: 06 November 2009 14:06 > To: ruby-talk ML > Subject: Re: encapsulation issue > > 2009/11/6 David A. Black : > > Hi -- > > > > On Fri, 6 Nov 2009, James French wrote: > > > >> Hi, > >> > >> Is there any way of providing read only access to an array? (problem > shown > >> by code below). > >> > >> class A > >> > >>  def initialize > >>   @dependencies = [] > >>  end > >> > >>  # intended to be read only access > >>  def dependencies > >>   @dependencies > >>  end > >> > >>  def addDependency(d) > >>   @dependencies << d > >>   puts "adding #{d}" > >>  end > >> end > >> > >> > >> a = A.new > >> a.addDependency("foo") > >> a.dependencies << "bar" # encapsulation subverted > >> > >> puts a.dependencies   # foo and bar both in array > > > > You can freeze the array: > > > >  a = [].freeze > >  a << 1          # TypeError: can't modify frozen array > > > > > > You could also dup it: > > class A > def dependencies > @dependencies.dup > end > end > > a = A.new > a.addDependency "foo" > a.dependencies << "bar" > puts a.dependencies # => ["foo"] I don't think it solves it that nicely because as well as duplicating data which doesn't feel good, you've then got a line that looks as though it does something but doesn't. I guess it could raise an error somehow.