首页 > 其他 > 详细

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

时间:2019-04-04 20:41:46      阅读:109      评论:0      收藏:0      [点我收藏+]

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(5) { [1, 2, 3] }的差别

原文:https://www.cnblogs.com/xfgnongmin/p/10656656.html

(0)
(0)
   
举报
评论 一句话评论(0
分享档案
最新文章
教程昨日排行
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!