Array assign vs. append behavior

The following behavior looks to me like the assign method is processing visited by value, whereas the append method is treating it as a reference:

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"]

Can someone explain this behavior?

This is not a question about whether Ruby supports pass by reference or pass by value, but rather about the example provided below, and why two methods that purportedly do the same thing exhibit different behaviors.


You redefine local variable in the first method.

This is the same as

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

And in the second method:

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/96236.html

上一篇: Gulp源地图和sass问题

下一篇: 数组分配与追加行为