From: "Brett H. Williams" Date: 2003-04-26T01:13:29+09:00 Subject: Re: freezing Array/Hash length On Apr 25, gabriele renzi wrote: > Hi gurus & nubys, > I just felt in a problem where I'd like to have a fixed size > Array/Hash [1]. > > BTW if I simply freeze my object I can't change the length, but > neither the object , so I have to do something like this > > def add_myarr(x) > @myarr.push x if @myarr.last < MAX_LENGTH > end > > Tjhis works fine cause I just put objects in the array trough this > method, but looks ugly, and I suppose that must be a better way to do > this. > Anyone out there could help me ? I'm not sure but my first post didn't make it apparently... First I don't think myarr.last < MAX_LENGTH does what you want: irb(main):001:0> ar = ["foo", "bar"] ["foo", "bar"] irb(main):002:0> MAX_LENGTH = 2 2 irb(main):003:0> ar.last < MAX_LENGTH TypeError: failed to convert Fixnum into String from (irb):3:in `<=>' from (irb):3:in `<' from (irb):3 I think you want to check size, not the last element. At any rate, why not: class FixedArray < Array def push(x) super(x) if size() < MAX_LENGTH end def []=(idx,x) super(idx,x) if idx < MAX_LENGTH - 1 end end You'd still have to be careful of other methods that might increase the length of an array. > [1] damn, I always wanted a variable length array when using java.. like a Vector?