Array.new(5, [1, 2, 3]) or Array.new(5) { [1, 2, 3] }的差别

Array.new(5, [1, 2, 3]) or Array.new(5) { [1, 2, 3] }

Array.new(size, default_object) creates an array with an initial size, filled with the default object you specify. Keep in mind that if you mutate
any of the nested arrays, you'll mutate all of them, since
each element is a reference to the same object.

array = Array.new(5, [1, 2, 3])
array.first << 4
array # => [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

Array.new(size) { default_object } lets you create an array with
separate objects
.

array = Array.new(5) { [1, 2, 3] }
array.first << 4
array #=> [[1, 2, 3, 4], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

Look up at the very top of the page you linked to, under the section entitled "Creating Arrays" for some more ways to create arrays.

上一篇:C# 阳历转农历


下一篇:Why does typeof array with objects return “Object” and not “Array”?