gpt4 book ai didi

Ruby 数组操作内部方法

转载 作者:数据小太阳 更新时间:2023-10-29 07:09:59 24 4
gpt4 key购买 nike

在下面,input_1 发生了变化:

def method_1(a)
a << "new value"
end

input_1 = []
method_1(input_1)
input_1 #=> ["new value"]

在下面,input_2 没有改变:

def method_2(a)
a = ["new value"]
end

input_2 = []
method_2(input_2)
input_2 #=> []

为什么 input_1 改变而 input_2 没有改变?

最佳答案

它归结为使用“按值传递引用”的 Ruby。

您遇到的确切情况在 this excellent blog post 中有所描述。 .

要点:

method_1 中,您正在更改两个不同变量(input_1a)都指向的对象的值。

method_2 中,您将一个全新的对象重新分配给两个变量之一 (a)。

关于Ruby 数组操作内部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54090261/

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