为什么这个Ruby方法通过引用

时间:2015-07-19 22:28:37

标签: ruby parameters reference pass-by-reference pass-by-value

我回答this问题并偶然发现了一些奇怪的事情。 Ruby通过值传递其参数,但变量本身是引用。 那么为什么第一种方法似乎通过引用传递它的参数呢?

require 'set'
require 'benchmark'

def add_item1!(item, list)
  list << item unless list.include?(item)
end

def add_item2(item, list)
  list |= [item]
end

def add_item3(item, list)
  set = Set.new(list)
  set << item
  list = set.to_a
end

array1 = [3,2,1,4]
add_item1!(5, array1)
p array1 # [3, 2, 1, 4, 5]

array2 = [3,2,1,4]
add_item2(5, array2) 
p array2 # [3, 2, 1, 4]

array3 = [3,2,1,4]
add_item3(5, array3)
p array3 # [3, 2, 1, 4]

1 个答案:

答案 0 :(得分:5)

非混淆的术语是Call by Object-Sharing 原始对象(并且复制/克隆/复制)被传递。

  

通过共享调用的语义与通过引用调用的不同之处在于对函数内函数参数的赋值对调用者不可见

在Ruby 重新分配[local]参数无效对调用者,因为使用Call by Reference。

在这个示例代码中,它显然具有Call by Reference语义;或第二和第三种情况,它们分配回本地变量,但否则不会修改原始对象,就像第一种情况一样。

在较低级别&#39;实现是[引用参数]的值调用 - 也就是说,内部Ruby使用指针和诸如此类的东西 - 这就是为什么有时候重载短语&#34;通过引用调用&#34;使用,经常忘记&#34;按值&#34;部分..并导致这种混乱。

def add_item1!(item, list)
  # MUTATES the list object, which is the original object passed
  # (there is no copy/clone/duplication that occurred)
  list << item unless list.include?(item)
end

def add_item2(item, list)
  # this creates a NEW list and re-assigns it to the parameter
  # re-assigning to a local parameter does not affect the caller
  # the original list object is not modified
  list |= [item]
end

def add_item3(item, list)
  set = Set.new(list)
  set << item
  # this creates a NEW list from set and re-assigns it to the parameter
  # re-assigning to a local parameter does not affect the caller
  # the original list object is not modified
  list = set.to_a
end