Nex
Nex

Reputation: 1623

Ruby: assignment to elements of an array

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?

Upvotes: 2

Views: 81

Answers (1)

Pascal
Pascal

Reputation: 8637

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]

Upvotes: 2

Related Questions