Using .clear method in Ruby [duplicate]

你说的曾经没有我的故事 提交于 2019-12-12 01:48:03

问题


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?


回答1:


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



回答2:


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!)


来源:https://stackoverflow.com/questions/30315197/using-clear-method-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!