Newbiest ? ever

O

Orion Hunter

(ruby 1.8.0 Linux)

I don't understand why I get the following behavriour:

irb(main):001:0> matrix = Array.new( 3, Array.new( 4, 0 ) )
=> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
irb(main):002:0> matrix[0][0] = 1
=> 1
irb(main):003:0> matrix
=> [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
irb(main):004:0>

I would have expected the assignment of matrix[0][0] to produce a matrix:
[[1,0,0,0],[0,0,0,0][0,0,0,0]]

What am I not getting here?

_________________________________________________________________
Plan your next US getaway to one of the super destinations here.
http://special.msn.com/local/hotdestinations.armx
 
K

Kent S.

Because, matrix = Array.new( 3, Array.new( 4, 0 ) )
creates an array with three elements all poining to the same array
object. What you need is something like that:

matrix = Array.new( 3 ) { Array.new( 4, 0 ) }

/kent
 
G

gabriele renzi

il Tue, 10 Feb 2004 02:56:28 +0900, "Orion Hunter"
(ruby 1.8.0 Linux)

I don't understand why I get the following behavriour:

irb(main):001:0> matrix = Array.new( 3, Array.new( 4, 0 ) )
=> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
irb(main):002:0> matrix[0][0] = 1
=> 1
irb(main):003:0> matrix
=> [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
irb(main):004:0>

I would have expected the assignment of matrix[0][0] to produce a matrix:
[[1,0,0,0],[0,0,0,0][0,0,0,0]]

What am I not getting here?

Array.new(num,object) just creates num refernces to object:
irb(main):001:0> a=Array.new(3,'yo')
=> ["yo", "yo", "yo"]
irb(main):002:0> a[0].id
=> 20896272
irb(main):003:0> a[1].id
=> 20896272

what you want is different object with the same value, you can do this
with:
irb(main):004:0> a=Array.new(3) {'yo'}
=> ["yo", "yo", "yo"]
irb(main):005:0> a[0].id
=> 20863668
irb(main):006:0> a[1].id
=> 20863656

so you should write:

matrix= Array.new(3) do
Array.new(4,0)
end

or just do:
require 'matrix'
:)
 

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

Similar Threads


Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top