Ruby - Arrays
The following code is intended to create an array of 3 separate empty arrays. What is the problem?
arr = Array.new(3, []) arr[0] << 1 puts arr.inspect
arr = Array.new(3, []) arr[0] << 1 puts arr.inspect
Array.new(3, []) creates 3 references to the same empty array, not 3 separate arrays.arr[0] << 1 runs, it adds 1 to the shared array, so all elements show the change.15+ quiz questions · All difficulty levels · Free
Free Signup - Practice All Questions