码迷,mamicode.com
首页 > 其他好文 > 详细

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

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

标签:phoenix   img   strong   nim   cti   arrays   hat   each   https   


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] }的差别

标签:phoenix   img   strong   nim   cti   arrays   hat   each   https   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
分享档案
周排行
mamicode.com排行更多图片
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!