Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Unexpected Multi Assignment

Tags:

ruby

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", []], [[], []], [[], []], [[], []]]
like image 321
userFriendly Avatar asked Dec 21 '25 17:12

userFriendly


2 Answers

In that way you use the same reference for every sub array. Try this way

@master = Array.new(4) { Array.new(2) { Array.new } }
like image 168
Ursus Avatar answered Dec 23 '25 07:12

Ursus


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.

like image 40
Gerry Avatar answered Dec 23 '25 08:12

Gerry