On Wed, Jun 26, 2002 at 08:13:05PM +0900, Tom Sawyer wrote:
> here's something i thought was interesting:
> (note that the comments are intended)
> 
> class Tt
> 
>   #attr_accessor :h  # no access to h!
> 
>   def initialize
>     @h = {}
>     @h['test'] = '1..'
>   end
>   
>   def [](xp)        # only want to allow reading
>     @h[xp]
>   end
>   
>   #def []=(xp, ap)  # no assignment allowed!
>   #  @h[xp] = [ap]
>   #end
> 
> end
> 
> tt = Tt.new
> tt['test'] << '..2'         # how come you can do me?
> tt['test'] = '1....2'       # if you can't do me!
> 
Well, you are returning a pointer to the object.
How about 

  def [](xp)
    @h[xp].dup
    # or, just to be sure
    #Marshal.load(Marshal.dump(@h[xp]))
  end

Jim
> 
> it seems to me that the main point of accessors and the []= method is to
> control accessiblity to a class' instance variables. right? but as this
> example shows, there are ways in which "back-doors" exist.
> 
> shouldn't there be better control of such thing? i came across this when
> i was actually trying to create a []<< method, and realized that i have
> never seen such a beast before! shouldn't such a thing exist?
> 
> ~transami
> 
> 

-- 
Jim Freeze
If only I had something clever to say for my comment...
~