Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array assign vs. append behavior

Tags:

ruby

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.

like image 248
FloatingRock Avatar asked Apr 28 '17 11:04

FloatingRock


People also ask

What is the difference between append () and + () in an array?

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.

What is array append in Ruby?

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.

How do I append a variable to an array in Python?

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.

Should Microsoft keep “ append to array variable with type” 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.


2 Answers

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"] 
like image 194
mikdiet Avatar answered Sep 28 '22 22:09

mikdiet


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"]
like image 39
Eric Duminil Avatar answered Sep 28 '22 22:09

Eric Duminil