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.


posted on 2019-04-04 19:18  xfgnongmin  阅读(153)  评论(0编辑  收藏  举报

导航