Why one array continues to grow after repeated call

Rick Denatale wrote:

On Thu, Sep 18, 2008 at 9:27 AM, Li Chen [email protected] wrote:

array. Therefore @b1 becomes, each time around the loop,
[10]
[10,10]
[10,10,10]
[10,10,10,10]

How come this loop happan? I don’t want a loop here.

Because that’s what you coded:

irb(main):008:1* def method2
irb(main):009:2> (method1.size).times{@b1<<10}
irb(main):010:2> return @b1
irb(main):011:2> end

$ qri Integer#times
---------------------------------------------------------- Integer#times
int.times {|i| block } => int

 Iterates block int times, passing in values from zero to int - 1.

It’s not really clear what you are trying to do with your two methods,
why
not just initialize both instance variable in the intialize method?

class A
def initialize
@a1 = [1,2,3,4]
@b1 = [10][email protected] # or more clearly just [10, 10, 10, 10]
end

def method1
@a1
end

def method2
@b1
end
end

The script in the OP is a simple version of another more lenghy one.

@a1 comprise all the file names from a folder.
@b1 comprise all the file names from another folder.
the construction of @b1 is dependent on @a1.
after initialize I want to check the status of @a1 and @b1.
out of curiossity I call both method1 and method2 more than once.

If I initialize both @a1 and @b1 in initialize method there would many
lines there. In order to keep the method short and easy to read I want
to keep each step in a different method.But I also want to initialize
both of them in initialize method. This is the reason why I put method1
and method2 in initialize method. I guess I misunderstood how method is
called in Ruby. I think I can retrieve the status of @a1 and @b1 by
writing accessor/getter. This way I would not mess up with the method
call.

I didn’t realize this post causes so much discussion when I posted. I
really appricate you guys spending your times and explaining the
problem.

Li