From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2002-01-17T03:55:38+09:00 Subject: Re: Protecting a member hash 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. Phil