Array assignment versus added behavior

The following behavior looks like the assign method treats visited by value, while the append method treats it as a link:

 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 anyone explain this behavior?

It is not a question of whether Ruby supports by reference or is passed by value, but rather of the example below, and why the two methods that supposedly do the same thing exhibit different types of behavior.

+7
ruby
source share
2 answers

You are redefining a 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"] 
+3
source share

Here's a modified version of MyClass#assign that 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"] 
+1
source share

All Articles