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.
The array.append operation inserts the array (or any object) into the end of the original array, which results in a reference to self in that spot (hence the infinite recursion). The difference here is that the + operation acts specific when you add an array (it's overloaded like others, see this chapter on sequences) by concatenating the element.
Ruby | Array append () function Last Updated : 07 Jan, 2020 Array#append () is an Array class method which add elements at the end of the array.
To find it, you can search for “Append to array variable” action or go to “Built-in”: You won’t probably see it in the main options, so you’ll need to expand until you dine the “Variable” group. Pick “Variable.” Select the “append to string variable” action.
Even if Microsoft has to keep the “append to array variable” action as is so as not to break compatibility, it will help a lot of people if either: The action would have an additional parameter with the definition of the type For example, have another action called “append to an array variable with type” action.
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"]
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With