> -----Original Message----- > From: Gavin Sinclair [mailto:gsinclair / gmail.com] > Sent: 06 November 2009 23:56 > To: ruby-talk ML > Subject: Re: encapsulation issue > > On Nov 7, 12:50 ¨Âí¬ ÊáíåÆòåîãè ¼Êáíåó®Æòå®®®Àîáôõòáìíïôéïî®ãïí¾ > wrote: > > > > Is there any way of providing read only access to an array? [...] > > > > > > a = A.new > > a.addDependency("foo") > > a.dependencies << "bar" # encapsulation subverted > > Ask yourself if it's really necessary to implement #dependencies. > (The answer may be 'yes'; I'm just saying don't assume it is.) > > For instance, you could provide access to the dependencies like this > > class A > # initialise and add_dependency as before > > include Enumerable > def each(&block); @dependencies.each(&block); end > > def [](n) > @dependencies[n] # possibly .dup this > end > end > > a = A.new > a.add_dependency "foo" > a.each do ... end > a.map { ... } > a.grep(...) > a[5] > > I've often found, when wrapping a basic data type, that I don't need > access to the 'guts' of that type; I only need to do a certain set of > things, so I implement them and leave it at that. > > -- > Gavin Sinclair Thanks for that. I think I may go that way.