[英]Create array of empty subarrays in Ruby
I want to create an array of n
number of distinct empty subarrays. 我想创建一个
n
个不同的空子数组的数组。
Is this the best way? 这是最好的方法吗?
Array.new(n){ [] }
It was as follows, but I modified after reading comments: 内容如下,但是我在阅读评论后进行了修改:
Array.new(n){ |_| [] }
I tried: 我试过了:
Array.new(n, [])
but it creates an array with all the subarrays being the same object, which I do not want. 但是它创建了一个数组,所有子数组都是同一个对象,我不希望这样。
All the proposed method to get this array [[], [], [],...]
works fine: 所有建议的获取此数组
[[], [], [],...]
可以正常工作:
Array.new(n, []) # the best, 20 times faster
Array.new(n){ [] }
n.times.map { [] }
The first is the fastest, so the best, but works strangely (see next). 第一个是最快的,所以是最好的,但是效果很奇怪(请参阅下一个)。
it created an array with all the sub arrays being the same object
它创建了一个数组,所有子数组都是同一个对象
If i get the point, you mean that whit the methods described happens what follows: 如果我明白这一点,则意味着所描述的方法发生以下情况:
a = Array.new(5, [])
p a # => [[], [], [], [], [], [], [], [], [], []]
p a.map { |e| e.object_id} # => [70189488740180, 70189488740180, 70189488740180, 70189488740180, 70189488740180]]
The object is the same, so if you try to fill subarrays with values, all of the subarrays assume the same value (replication): 对象是相同的,因此,如果您尝试用值填充子数组,则所有子数组均假定为相同的值(重复):
a[0][0] = 10
p a # => [[10], [10], [10], [10], [10]]
To avoid this don't pass a default value, but map to empty array instead: 为避免这种情况,请不要传递默认值,而应映射到空数组:
a = Array.new(5).map{ |e| [] }
p a # => [[], [], [], [], []]
Or pass the block 或通过障碍
a = Array.new(5){ [] }
a = 5.times.map { [] }
Now each subarray is an independent object: 现在,每个子数组都是一个独立的对象:
p a.map { |e| e.object_id} # => [70253023825640, 70253023825620, 70253023825600, 70253023825580, 70253023825560]
And if you insert some values there is no replication: 而且,如果您插入一些值,则不会进行复制:
a[0][0] = 10
a[1][0] = 20
p a # => [[10], [20], [], [], []]
Array.new(n){ [] }
is totally fine! Array.new(n){ [] }
很好! The block ensures that a new instance of Array is created n times. 该块可确保创建新的Array实例n次。 As you pointed out, you would otherwise reference the same object (instance of Array) n times.
如您所指出的,否则,您将多次引用同一对象(Array的实例)。
Please try this. 请尝试这个。 It work for me.
它对我有用。
n = 15
arr = Array.new(n)
arr.map!{ |x| x = [] }
Now, putting value in the array. 现在,将值放入数组。
arr[0][0] = 10
arr[5][0] = 50
p arr # => [[10], [], [], [], [], [50], [], [], [], [], [], [], [], [], []]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.