In article <20020116131656.A93722 / freebsdportal.com>,
Jim Freeze  <jfreeze / freebsdportal.com> 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