From: "David A. Black" Date: 2009-11-07T02:22:44+09:00 Subject: Re: encapsulation issue Hi -- On Sat, 7 Nov 2009, James French wrote: > > >> -----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... Whoops. I had a nagging feeling I wasn't giving the question enough attention when I answered :-) I would probably favor the dup approach for the reader. In the end, someone can get around it: a.instance_eval { @dependencies << "bar" } But it would at least keep away casual and accidental appenders. 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)