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

Posted xfgnongmin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Array.new(5, [1, 2, 3]) or Array.new { [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.


以上是关于Array.new(5, [1, 2, 3]) or Array.new { [1, 2, 3] }的差别的主要内容,如果未能解决你的问题,请参考以下文章

======第五章设备管理======

ruby hash value array append new element

powershell 能声明二维数组么

判断3带2以及成不成立的5张牌函数

php输出数组第二个

for循环二维数组的取值方式?