Why both pieces of code are not printing the same thing. I was intending the first piece to produce the output of the second
a=Array.new(5,Array.new(3))
for i in (0...a[0].length)
a[0][i]=2
end
p a
# this prints [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]]*
a=Array.new(5).map{|d|d=Array.new(3)}
for i in (0...a[0].length)
a[0][i]=2
end
p a
# this prints [[2, 2, 2], [nil, nil, nil], [nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
This one
Creates an array that contains the same array object within it five times. It’s kinda like doing this:
Where this one:
Creates a new 3 item array for each item in the parent array. So when you alter the first item it doesn’t touch the others.
This is also why you shouldn’t really use the
ArrayandHashconstructor default arguments, as they don’t always work they way you might expect.