-1

When we initialize an array of arrays using

ar = Array.new(2, [0, -1])

It creates an array which looks like [[0, -1], [0, -1]]

But when we change the value in the inner array, it gets reflected in all elements of the array.

ar[0][0] = 5
puts ar

[[5, -1], [5, -1]]

Seems the same object is getting inserted into each index of the outer array. What is the correct way to prevent this?

0

1 Answer 1

1

Use the Array.new block form:

ar = Array.new(2) { [0, -1] }

Since the array literal [0, -1] is scoped to the block, a new instance is created on every invocation. You can test this by adding a puts or similar in the block:

ar = Array.new(2) { |n| puts "called for element #{n}"; [0, -1] }

results in:

called for element 0
called for element 1
=> [[0, -1], [0, -1]]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.