0

Couldn't explain my question succinctly enough in the title, so I'm putting it here. It will actually be easier to show the code before asking my question:

array1 = []
array2 = [1,2,3]

array1 = array2
#=> array1 = [1,2,3]

array2.clear

#=> array1 = []
#=> array2 = []

Why does using the .clear method on the second array also clear what is in the first array? I guess what I'm asking is, once we set array1 = array2, why is array1 affected by the .clear we apply to array2? It seems that array1 = array2 will hold true for the duration of my script, is this right?

In order for array1 to remain unchanged once I do array2.clear, would I need to implement array1 = array2 a different way, such as using a for loop and .unshifting elements from array2 and .pushing them over to array1?

2
  • 1
    Did you see this answer? stackoverflow.com/questions/3672399/…. Great explanation of references. Also, for bonus points, suggestion that you can use .clone to create a true copy. Commented May 19, 2015 at 1:13
  • Thanks for that link. I feel silly now.. can I delete my question? lol Commented May 19, 2015 at 1:16

2 Answers 2

7

When you do

array1 = array2

array1 and array2 reference to the same Array object now. So any modifications you make to either will affect to the other.

array1.object_id
# => 2476740
array2.object_id
# => 2476740

See? They have the same object_id.


If this behavior is not what you expected, try

array1 = array2.dup

or

array1 = array2.clone
Sign up to request clarification or add additional context in comments.

1 Comment

I think using object_id is the best demonstration of what is happening.
1

You may be confused because with integers it seems like it works differently:

a = 6  # puts "6" into a memory location, and point "a" to it
b = a  # points "b" to the same memory location as "a"
b = 7  # puts "7" into a memory location, and point "b" to it.

puts a  # 6
puts b  # 7

Note that with the = you are telling the variable to point to an object at a certain memory address. Contrast this with your question:

array1 = []  # put empty array in memory and points array1 to it
array2 = [1,2,3]  # put [1,2,3] array into memory and point array2 to it

array1 = array2  # make array2 point to same location as array1
#=> array1 = [1,2,3] 

array2.clear  # tell ruby to clear the memory location pointed to by array2 (uh oh, array1 pointing to same place!)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.