数组分配与追加行为

以下行为在我看来像的assign方法是处理visited按值,而append的方法是把它当作一个参考:

class MyClass
  def assign(visited)
    visited += ["A"]
  end
  def append(visited)
    visited << "A"
  end
end

instance = MyClass.new
visited = []

instance.assign(visited)
visited # => []

instance.append(visited)
visited # => ["A"]

有人可以解释这种行为吗?

这不是一个关于Ruby是支持按引用传递还是按值传递的问题,而是关于下面提供的示例,以及为什么两个声称做同样事情的方法表现出不同的行为。


您在第一种方法中重新定义局部变量。

这与之相同

visited = []
local_visited = visited
local_visited = ['A']
visited
# => [] 

在第二种方法中:

visited = []
local_visited = visited
local_visited << 'A'
visited
# => ["A"] 

这里是MyClass#assign的一个修改版本,它改变visited

class MyClass
  def assign(visited = [])
    visited[0] = "A"
  end
  def append(visited = [])
    visited << "A"
  end
end

instance = MyClass.new
visited = []

instance.assign(visited)
p visited # => ["A"]

visited = []
instance.append(visited)
p visited # => ["A"]
链接地址: http://www.djcxy.com/p/96235.html

上一篇: Array assign vs. append behavior

下一篇: Google Search with Alamofire Fails (iOS, Swift, JSON, HTML)