From: Jim Freeze Date: 2002-01-17T04:09:34+09:00 Subject: Re: Protecting a member hash On Thu, Jan 17, 2002 at 03:55:38AM +0900, Phil Tomson wrote: > In article <20020116131656.A93722@freebsdportal.com>, > Jim Freeze wrote: > >Hi: > > > >I have a class that stores data in a hash. > >I would like the user to be able to retrieve > >values from the hash, but not modify it. > > > >class Test > > attr_reader :entity > > def initialize > > @entity = {'a'=>"fred"} > > end > >end > > > >t = Test.new > >p t.entity #=> {"a"=>"fred"} > >t.entity['a'] = "changed" > >p t.entity #-> {"a"=>"changed"} > > > > > >Other than freezing @entity, is it possible > >top protect it from being changed? > > > > Why not just define a '[]' method, but not a '[]=' method in your class > and don't use the attr_reader. Like: > > class Test > def initialize > #HasA hash: > @entity = {'a'=>"fred"} > end > > def [](key) > @entity[key] > end > > end > > t = Test.new > p t['a'] #this will work > t['b']="Error" #this will raise an error > > So basically, you're hiding the hash from the outside world. Well. that would work, but the real story is that I have multiple hashes in the class. So, the single Test#[] is limiting. I suppose I would write a class for each hash. Is there a cheaper way? Jim > > Phil > -- Jim Freeze Today is a fine day for Ruby programming. www.freeze.org