userFriendly
userFriendly

Reputation: 484

Array Unexpected Multi Assignment

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

Answers (2)

Ursus
Ursus

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

Gerry
Gerry

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

Related Questions