This code puts the same line in each row of array:
def create_array(size)
array = [] # Create an Array object, "array"
line = [] # Create an Array object, "line"
size.times { line << "*" }
# The following line puts the SAME Array object, "line", into
# array "size" times
#
size.times { array << line }
array
end
You need to put a new one in each time. I assume by size you mean that's a square matrix:
def create_array(size)
Array.new(size) { Array.new(size, "*") }
end
Here, Array.new(n, elt) creates a new Array object of length n and filled with element, elt. See Ruby Array "new" method. Note that trying to do something like this has a similar issue as the original problem:
Array.new(size, Array.new(size, "*"))
In this case, Array.new(size, "*") occurs once and as passed as the second argument to the "outer" Array.new(size, ...), so each row here is also the same Array object. Passing the block to Array.new(...) as above generates a separate Array.new(size, "*") call for each row.
create_arrayputs the samelinein each row of your 2D array. And what'ssize? Is it a square matrix, withsizerows andsizecolumns?array. So when you change one, you've changed them all.