Can someone explain this?
def digit_block(size = 1)
col = 2 + 1*size
row = 1 + 2*size
r = []
for i in 0...col
r.push ' '
end
a = []
for i in 0...row
a.push r
end
a
end
block = digit_block
puts block.inspect
block[1][2] = 'x'
puts block.inspect
outputs:
[[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
[[" ", " ", "x"], [" ", " ", "x"], [" ", " ", "x"]]
My understanding is block[1][2] only changes the cell at row 1 column 2, but why it changes all the cell in column 2?
So every element in
blockis the same object.Update:
You need to make a new array for every element, your code could be rewrote as below: