Ruby方法内部的数组操作 [英] Ruby array manipulation inside method

查看:59
本文介绍了Ruby方法内部的数组操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下,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中的变量是对值的引用.在您的情况下,变量a保存对数组的引用.

With a bit of simplification we can say that a variable in Ruby is a reference to a value. In your case variable a holds a reference to an array.

a <<(a.append)突变存储在变量a中的.引用未更改,但值已更改.是method_1

a << (a.append) mutates the value stored in variable a. The reference is not changed, but the value did. It's the case of method_1

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

赋值=更改存储在变量中的引用-它开始指向另一个值.引用在传递给方法时被复制.因此,当您致电

Assignment = changes the reference stored in a variable - it starts to point to a different value. References are copied when passed to a method. Because of that when you call

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

您只能更改存储在方法本地的a中的引用,而无需更改存储在input中的引用或该引用所指向的值(和[]的数组).

You only change a reference stored in a that is local to the method, without any change to the reference stored in input nor to the value (and array of []) that is pointed by this reference.

这篇关于Ruby方法内部的数组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆