Creating Arrays Through a Loop

S

Squawk Boxed

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
 
R

Robert Klemme

2010/2/1 Squawk Boxed said:
I was wondering if it was possible to create a series of arrays through
a loop. =A0This doesn't work (I think):

for num in 1..10
=A0array_num =3D 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 =3D []
10.times { arrs << Array.new }

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

Cheers

robert


--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 
M

Marnen Laibow-Koser

Squawk said:
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,
 
A

Aldric Giacomoni

Squawk said:
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.
 
R

Robert Klemme

2010/2/1 Aldric Giacomoni said:
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 =3D 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 `<main>'


Cheers

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top