From: James French Date: 2009-11-07T00:57:42+09:00 Subject: Re: encapsulation issue > -----Original Message----- > From: David A. Black [mailto:dblack@rubypal.com] > Sent: 06 November 2009 14:01 > To: ruby-talk ML > Subject: Re: encapsulation issue > > 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 > > > David > > -- > The Ruby training with D. Black, G. Brown, J.McAnally > Compleat Jan 22-23, 2010, Tampa, FL > Rubyist http://www.thecompleatrubyist.com > > David A. Black/Ruby Power and Light, LLC (http://www.rubypal.com) But then I can't legitimately push to it in addDependency...