The Strangeness of Arrays

R

Roger Bannister

Hi

The behaviour below has me completely confuzzled. Why on earth does my
array suddenly have all rows equal to the last row?

Can anyone tell me if this is expected; or if I have to start wearing my
Stupid Hat again.

Thanks
R

irb(main):014:0> @t = Array.new(5, Array.new(4))
=> [[nil, nil, nil, nil], [nil, nil, nil, nil], [nil, nil, nil, nil],
[nil, nil, nil, nil], [nil, nil, nil, nil]]
irb(main):025:0> row = 0
=> 0
irb(main):026:0> while (row <= 4)
irb(main):027:1> column = 0
irb(main):028:1> while (column <= 3)
irb(main):029:2> printf(".%d,%d: %d. ", column, row, @t[row][column] =
row+column)
irb(main):030:2> column += 1
irb(main):031:2> end
irb(main):032:1> printf("\n")
irb(main):033:1> row += 1
irb(main):034:1> end
0,0: 0. .1,0: 1. .2,0: 2. .3,0: 3.
0,1: 1. .1,1: 2. .2,1: 3. .3,1: 4.
0,2: 2. .1,2: 3. .2,2: 4. .3,2: 5.
0,3: 3. .1,3: 4. .2,3: 5. .3,3: 6.
0,4: 4. .1,4: 5. .2,4: 6. .3,4: 7.
=> nil
irb(main):035:0> @t
=> [[4, 5, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7], [4, 5, 6, 7]]
 
H

Hal Fulton

Roger said:
Hi

The behaviour below has me completely confuzzled. Why on earth does my
array suddenly have all rows equal to the last row?

Can anyone tell me if this is expected; or if I have to start wearing my
Stupid Hat again.

It's the strangeness of objects, not arrays. See below...
Thanks
R

irb(main):014:0> @t = Array.new(5, Array.new(4))

This fills @t with five references to the same four-item array.

If you change one, you change them all.

I think in recent Ruby you can do this:

@t = Array.new(5) { Array.new(4) }

and you'll get different sub-arrays. Try it...


Hal
 
R

Roger Bannister

Hal said:
It's the strangeness of objects, not arrays. See below...



This fills @t with five references to the same four-item array.

If you change one, you change them all.

I think in recent Ruby you can do this:

@t = Array.new(5) { Array.new(4) }

and you'll get different sub-arrays. Try it...


Hal
Right, it's the hat for me! I'd completely forgotten the basic example
of a = 1; b = a.

Thanks guys.
 

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

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top