From: Gavin Kistner Date: 2005-06-03T12:24:54+09:00 Subject: Re: Implementing a Read-Only array --Apple-Mail-1--124546398 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed On Jun 2, 2005, at 4:54 PM, Ara.T.Howard wrote: > On Fri, 3 Jun 2005, Gavin Kistner wrote: >> However...if I've undef'd #[]=, then that won't work, right? > but that means that not even you can mutate it. if not even you > can mutate it > why not just use Object#freeze? Well, if I alias it first I can. (This is using my original non- delegated method, since the delegator technique (as I've currently implemented it) does allow the custom mutator method to affect the wrapped object directly. class Array def mutate(k,v); self[k]=v; end end class ImmutableArray < Array alias_method :'__ro_[]=', :'[]=' %w{ << []= clear concat delete delete_at delete_if fill flatten! insert map! pop push reject! replace reverse! shift slice! sort! uniq! unshift }.each{ |m| undef_method( m ) } end ro = ImmutableArray.new( [0,1,2] ) ro.send( :'__ro_[]=', 1, 'one' ) p ro #=> [0, "one", 2] ro.mutate( 2, 'two' ) #=> /Users/gavinkistner/Desktop/readonlyarray.rb:11:in `mutate': undefined method `[]=' for [0, "one", 2]:ImmutableArray (NoMethodError) from /Users/gavinkistner/Desktop/readonlyarray.rb:44 --Apple-Mail-1--124546398--