gpt4 book ai didi

ruby - Ruby 的 Array#to_a 方法有什么区别

转载 作者:数据小太阳 更新时间:2023-10-29 08:20:31 25 4
gpt4 key购买 nike

例如:

a = [1,2,3,4]
b = a
c = a.to_a
a.insert(0,0) #=> [0,1,2,3,4]
b #=> [0,1,2,3,4]
c #=> [0,1,2,3,4]

为什么数组bc的输出是一样的?如果我想获取数组 a 的副本,而不是引用数组,我应该使用哪种方法?

最佳答案

Why the output of array b and c is the same?

因为所有三个局部变量都引用相同的对象,如下所示:

a = [1,2,3,4]
b = a
c = a.to_a
a.object_id
# => 72187200
b.object_id
# => 72187200
c.object_id
# => 72187200

If i want to get a copy of array a, not a reference one , which method should i use?

然后使用a.dup。这里记录了Object#dup

a = [1,2,3,4]
b = a.dup
c = a.dup
a.object_id
# => 82139270
b.object_id
# => 82139210
c.object_id
# => 82134600
a.insert(0,0) # => [0, 1, 2, 3, 4]
b # => [1, 2, 3, 4]
c # => [1, 2, 3, 4]

Array#to_a says : Returns self.If called on a subclass of Array, converts the receiver to an Array object.

因此根据您的需要它不会有帮助。

关于ruby - Ruby 的 Array#to_a 方法有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18163027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com