2

I'm a beginner and I want to create a matrix. For example:

0 1 1
1 1 1
1 1 2

irb(main):001:0> t = [[1]*3]*3
=> [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
irb(main):002:0> (0...3).each do |x| t[x][x]=x end
=> 0...3
irb(main):003:0> t
=> [[0, 1, 2], [0, 1, 2], [0, 1, 2]] # why all values changed?

What's wrong?

0

1 Answer 1

2

The way you construct the array does not cretae new arrays for each row but references the same array for all rows:

t.each do |row|
  p row.object_id
end

# 70325094342320
# 70325094342320
# 70325094342320

It is the same as:

a = [1, 1, 1]
t = [a, a, a]

Try this to see the difference:

t = [[1] * 3, [1] * 3, [1] * 3]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.