Creating Arrays Through a Loop

I was wondering if it was possible to create a series of arrays through
a loop. This doesn’t work (I think):

for num in 1…10
array_num = Array.new
end

Squawk B. wrote:

I was wondering if it was possible to create a series of arrays through
a loop. This doesn’t work (I think):

for num in 1…10
array_num = Array.new
end

Of course that doesn’t work. You’re setting the same variable
(array_num) each time. What you should do is use an array of arrays:

array_of_arrays = Array.new(10) {Array.new}

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Squawk B. wrote:

I was wondering if it was possible to create a series of arrays through
a loop. This doesn’t work (I think):

for num in 1…10
array_num = Array.new
end

It works fine, but it will always assign the new array to the same
variable.

One idea is to create an array, and then add arrays as elements.

main_array = Array.new
(1…10).times { main_array << Array.new }

This may do what you want, but there may also be a more Ruby-ish way,
depending on why you need those arrays.

2010/2/1 Aldric G. [email protected]:

One idea is to create an array, and then add arrays as elements.

main_array = Array.new
(1…10).times { main_array << Array.new }

Either use (1…10).each or use 10.times - but (1…10).times won’t work:

irb(main):002:0> (1…10).times {|*a| p a}
NoMethodError: undefined method times' for 1..10:Range from (irb):2 from /opt/bin/irb19:12:in

Cheers

robert

Robert K. wrote:

2010/2/1 Aldric G. [email protected]:

One idea is to create an array, and then add arrays as elements.

main_array = Array.new
(1…10).times { main_array << Array.new }

Either use (1…10).each or use 10.times - but (1…10).times won’t work:

Whoops! That’s what I get for crossing two thoughts.

2010/2/1 Squawk B. [email protected]:

I was wondering if it was possible to create a series of arrays through
a loop. This doesn’t work (I think):

for num in 1…10
array_num = Array.new
end

Well, it does work - only you loose references to a newly created
Array immediately. You can try some of these variants:

arrs = []
10.times { arrs << Array.new }

arrs = Array.new(10) { Array.new }
arrs = (1…10).map { Array.new }

Cheers

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs