FloatingRock
FloatingRock

Reputation: 7065

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.

Upvotes: 7

Views: 193

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54223

Here's a modified version of MyClass#assign which mutates 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"]

Upvotes: 1

mikdiet
mikdiet

Reputation: 10018

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

Upvotes: 3

Related Questions