Reputation: 484
I have the following array:
@master = Array.new(4, Array.new(2, Array.new()))
=> [[[], []], [[], []], [[], []], [[], []]]
I'm attempting to assign the very first most value with:
@master[0][0] = "x"
=> "x"
But this is doing a multi assignment
@master
=> [["x", []], ["x", []], ["x", []], ["x", []]]
How do I assign only the first value? I'm hoping to get the following Array:
@master
=> [["x", []], [[], []], [[], []], [[], []]]
Upvotes: 2
Views: 46
Reputation: 30056
In that way you use the same reference for every sub array. Try this way
@master = Array.new(4) { Array.new(2) { Array.new } }
Upvotes: 6
Reputation: 10497
You are creating one array an assigning it to every element of the first array; try running this code:
@master.each { |e| puts e.object_id }
Output (your ids will be different):
70192803217260
70192803217260
70192803217260
70192803217260
As you can see, is the exact same object, so try using @master = Array.new(4) { Array.new(2) { Array.new() } }
instead, which will create a new array for each item in the first array.
Upvotes: 3