Freezing Array/Hash length

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 ?

thanks in advance

[1] damn, I always wanted a variable length array when using java…

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?

···

On Apr 25, gabriele renzi wrote:

First I don’t think myarr.last < MAX_LENGTH does what you want:

doh! I meant to write “length” not “last”…

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.

well, this is a slightly better solution, I just thought that could be
something like Array#fix_size that I (and ri) was’nt aware of…

[1] damn, I always wanted a variable length array when using java…

like a Vector?

sure, but doing
mine = (mySpecificClass) myVector.elementAt(10)
is way worst than
my = myArray[10]

:slight_smile:

anyway, thanks

···

il Sat, 26 Apr 2003 01:13:29 +0900, “Brett H. Williams” brett_williams@agilent.com ha scritto::