has any one tried this?

W

Wu Ning

My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts a

the result of a is
[[1], [1], [1]]
in irb..

I don't understand why.
I just wannt insert into a 1 into the third array of a.
 
F

Frederick Cheung

My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts a

the result of a is
[[1], [1], [1]]
in irb..

I don't understand why.
Array.new will insert the second argument you give into the array (3
times since that's what you've asked for). However it's the same array
(You can see this quite easily if you do Array.new(3,Array.new).map {|
x| x.object_id}). So a is not an array containing 3 arrays, it's an
array containing the same array 3 times.
a = Array.new(3) {[]}
should do the trick (since the block is called once for each element
of the array)

Fred
 
D

Daniel Lucraft

Wu said:
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts a

the result of a is
[[1], [1], [1]]
in irb..

I don't understand why.
I just wannt insert into a 1 into the third array of a.

After a = Array.new(3,Array.new()), a is an array containing three
references to the same object. There is only one array, but it is
repeated three times.

Do
a = []; 3.times { a << [] }
and you'll have three different arrays.

best,
Dan
 
C

Casimir

Wu Ning kirjoitti:
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts a

I suppose you wanted to type

irb(main):012:0> uber = [[], [], 3]
=> [[], [], 3]


Csmr
 
W

Wu Ning

Thanks,
I know what's going on now,
:)

Daniel said:
Wu said:
My ruby version is 1.8.6
a = Array.new(3,Array.new())
a[2]<<1
puts a

the result of a is
[[1], [1], [1]]
in irb..

I don't understand why.
I just wannt insert into a 1 into the third array of a.

After a = Array.new(3,Array.new()), a is an array containing three
references to the same object. There is only one array, but it is
repeated three times.

Do
a = []; 3.times { a << [] }
and you'll have three different arrays.

best,
Dan
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top