I do not understand why the two arrays (see below) are behaving differently.
dotnew = Array.new(5, [])
literal = [[], [], [], [], []]
dotnew[0] << 1
dotnew # => [[1], [1], [1], [1], [1]]
literal[0] << 1
literal # => [[1], [], [], [], []]
I do not understand why the two arrays (see below) are behaving differently.
dotnew = Array.new(5, [])
literal = [[], [], [], [], []]
dotnew[0] << 1
dotnew # => [[1], [1], [1], [1], [1]]
literal[0] << 1
literal # => [[1], [], [], [], []]
Because in dotnew
there is only one array and 5 references to it. When you change the array through one of the references, others see it too.
From the docs:
In the first form, if no arguments are sent, the new array will be empty. When a size and an optional obj are sent, an array is created with size copies of obj. Take notice that all elements will reference the same object obj.
In the literal case, there are 5 different arrays (each with one reference).
Perhaps, you wanted to do this:
dotnew = Array.new(5) { [] }
dotnew[0] << 1
dotnew # => [[1], [], [], [], []]