当传递一个Ruby数组作为参数,为什么`<<`追加而`+ =`不? [英] When passing a Ruby array as an argument, why does `<<` append while `+=` does not?

查看:136
本文介绍了当传递一个Ruby数组作为参数,为什么`<<`追加而`+ =`不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数组传递给函数和&LT的行为时,对面一个意想不到的结果跑了$ C>。

I ran across an unexpected result when passing an array to a function and the behavior of << vs +=.

谁能解释为什么下面的2个节目有不同的输出?

Can anyone explain why the following 2 programs have different output?

def build_results
  result = []

  [1, 2, 3].each { |value| concat_to_array(value, result) }

  result
end

def concat_to_array(value, arr)
  arr << value
end

build_results() # Will return [1,2,3].  As I would expect.

VS

def build_results
  result = []

  [1, 2, 3].each { |value| add_to_array(value, result) }

  result
end

def add_to_array(value, arr)
  arr += [value]
end

build_results() # Will return [], not what I expected!

我的理解是,在Ruby中的所有函数参数通过引用传递,所以改编+ = [值] 应该还是通过阵列上运行并且添加值。

My understanding is that in Ruby all function arguments are passed by reference, so arr += [value] should still be operating on the passed array and append the value.

这是不是这样的,它告诉我,我不明白 + = ℃之间的差异;&LT; 在这方面

This is not the case, which tells me I don't understand the difference between += and << in this context.

推荐答案

之间的主要区别在#&LT;&LT; #+ s表示#&LT;&LT; 只是阵列的实例方法,所以你只值添加到阵列的指定实例

The main difference between the #<<, and #+ s that #<< is just the Array's instance method, so you just add a value to the specified instance of Array

arr = []
arr.__id__ # => 68916130
arr << 10
arr.__id__ # => 68916130

但在#+ 的形式使用赋值运算符,其与新的实例替换参照的变量,并且该新的实例不应被传递到的uplevel #add_to_array 功能。

but in form of #+ is used assignment operator, which replace reference to a variable with a new instance, and that new instance shall not be passed into uplevel of the #add_to_array function.

arr = []
arr.__id__ # => 68916130
arr += [10]
arr.__id__ # => 68725310

注意: + = 意味着#+ 方法加上赋值运算符 = ,但是红宝石间preTER将其视为一个特定运营商不作为总和。

NOTE: That += implies the #+ method plus assignment operator =, however ruby interpreter treats it as a specific operator not as a sum.

形式改编改编= + [10] 不正常工作也。

def add_to_array(value, arr)
  arr = arr + [value]
end
build_results()
# => [] 

这篇关于当传递一个Ruby数组作为参数,为什么`&LT;&LT;`追加而`+ =`不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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