Reputation: 256
Decided to make a method for creating two-dimensional array. The array looks well, but when I'm trying to change the value, I change that value in all the sub-arrays, so it looks like this:
a[0][0] = 0
[[0, "", ""], [0, "", ""], [0, "", ""]]
Any ideas how to make it work properly?
Here's the method for creating the array:
def create_array(size)
array = []
line = []
size.times { line << "*" }
size.times { array << line }
array
end
Upvotes: 0
Views: 501
Reputation: 58244
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.
Upvotes: 1