0

I'm having some confusion about populating a new array with an existing array. It seems like if I set one array equal to the other, they become dynamically linked for the rest of the code. Is this a compiler attribute or am I not using the correct functions to store the values of one array in another? I hope this isn't an extremely basic question.

main_arr = [1, 2, 3, 4, 5]
temp_arr = main_arr
puts "Main: " + main_arr.to_s 
puts "Temp: " + temp_arr.to_s

main_arr.clear
puts "Main: " + main_arr.to_s 
puts "Temp: " + temp_arr.to_s

Output:

Main: [1, 2, 3, 4, 5]
Temp: [1, 2, 3, 4, 5]
Main: []
Temp: []
1
  • If a is your array, a.dup will create a "shallow" copy. Suppose, for example, a = [[1,2], [3,4]]. Then b = a.dup #=> [[1, 2], [3, 4]]. So far, so good. Now lets add an element to b: b << 'dog' #=> [[1, 2], [3, 4], "dog"]. a is unchanged: a #=> [[1,2], [3,4]]. Consider b[1][0] #=> 3. Now let's change that element of b and see what happens to a: b[1][0] = 'cat'; b #=> [[1, 2], ["cat", 4], "dog"]; a #=> [[1, 2], ["cat", 4]]. Not what you were expecting? That's because dup creates a "shallow" copy of a. Commented Jun 17, 2016 at 4:15

3 Answers 3

1

It's true, in your second line you are making temp_array point to the array object pointed by main_arr. If you want to make a copy of that array you can do

b = a.dup
Sign up to request clarification or add additional context in comments.

4 Comments

Ah perfect! It's odd that this isn't covered in the Ruby documentation for arrays...
That's because #dup is on Object: ruby-doc.org/core-2.3.1/Object.html#method-i-dup
You can find the owner of an instance method like this: Array.instance_method(:dup).owner #=> Kernel, or [].method(:dup).owner #=> Kernel. (Actually, Array.instance_method(:dup) #=> #<UnboundMethod: Array(Kernel)#dup> is enough, as the owner is shown in parenthesis.) Kernel's instance methods are documented in Object (see second paragraph), which can be a bit confusing. (Kernel's module methods are documented in Kernel.)
I read through the Object documentation and I know understand what's happening with clone and dup. I appreciate not only the help, but the supporting documentation.
0

when you do this: temp_arr = main_arr it means that temp_arr is pointing to main_arr address. use temp_arr = main_arr.dup to copy it instead.

main_arr = [1, 2, 3, 4, 5]
temp_arr = main_arr **means** temp_arr -> [1, 2, 3, 4, 5]

so, when you do this main_arr.clear -> [] and also temp_arr -> []

Comments

0

Try doing:

main_arr = [1,2,3,4,5]
temp_arr = main_arr.dup

main_arr.clear
puts main_arr # => []
puts temp_arr # => [1,2,3,4,5]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.