Nested arrays - what can be wrong with this?

T

Tim L

Can anyone explain why this code:

a = Array.new(3,Array.new(3,0))
a[1][1]=1
a.each {|r| puts r.join(', ')}

generates this output?

0, 1, 0
0, 1, 0
0, 1, 0

I was expecting this

0, 0, 0
0, 1, 0
0, 0, 0

Something wrong with my understanding of Ruby - or conceivably the set up on
my PC?

Tim L
 
D

Daniel Schierbeck

Tim said:
Can anyone explain why this code:

a = Array.new(3,Array.new(3,0))
a[1][1]=1
a.each {|r| puts r.join(', ')}

generates this output?

0, 1, 0
0, 1, 0
0, 1, 0

Try this:

ary = Array.new(3){Array.new(3, 0)}


Cheers,
Daniel
 
M

marek4130

Hi Tim,

The Array.new(3,0) is called only once. so a has 3 references to the
same array.
a[0] == a[1] will return true as will a[1] == a[2]

Instead try:
a = Array.new(3) {Array.new(3,0)}

have fun,
Marek
 
T

Tim L

Thank you guys
Hi Tim,

The Array.new(3,0) is called only once. so a has 3 references to the
same array.
a[0] == a[1] will return true as will a[1] == a[2]

Instead try:
a = Array.new(3) {Array.new(3,0)}

have fun,
Marek
Tim said:
Can anyone explain why this code:

a = Array.new(3,Array.new(3,0))
a[1][1]=1
a.each {|r| puts r.join(', ')}

generates this output?

0, 1, 0
0, 1, 0
0, 1, 0

I was expecting this

0, 0, 0
0, 1, 0
0, 0, 0

Something wrong with my understanding of Ruby - or conceivably the set up
on
my PC?

Tim L
 

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,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top