From: Ken Bloom Date: 2008-05-01T14:10:06+09:00 Subject: Re: How to create "def method(item)= (value)" ? On Wed, 30 Apr 2008 09:56:04 -0500, I単aki Baz Castillo wrote: > 2008/4/30, Ken Bloom : >> def initialize >> @params={} >> end >> >> def param >> @params >> end > > But I don't want that since it allows any self modification way (.strip! > .chomp! ...) and I just want to allow []= > > Thanks. In that case, do as I wrote further on and have the param function return a proxy that edits the params array in only the ways you want. class ParamsProxy def initialize hash #thanks to duck typing hash can be an Array instead, if you'd like @hash=hash end def [] key #with .dup here, mutating operations on the returned value #will not affect the values stored in the @hash #note that even attr_reader isn't this careful about the #objects that it returns, and so if you want behavior #like attr_reader, then omit the .dup here @hash[key].dup end def []= key,value @hash[key]=value end end class MyClass def initialize @params={} end def param ParamsProxy.new @params end end I presented this in rough outline before, without code, because there are many ways one could want to dress this up -- having some kind of validation code, or having the object.param[key]=value update something else entirely, or shoving the whole thing behind a nice attr_accessor- like interface. I don't have the time now to think through all of the possibilities involved to come up with a general solution, nor do I have a clear idea of exactly what your other constraints are. But start here, be creative, and let us know exactly what you do come up with. --Ken -- Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/