Both dup and clone return different objects, but modifying them alters the original object

元气小坏坏 提交于 2019-12-05 05:52:57
knut

dupand clone make new instances of the arrays, but not of the content, it is no deep copy.

See:

array0 = ['stuff', 'things']
array1 = array0.clone
array2 = array0.dup

puts "Array-Ids"
p array0.object_id
p array1.object_id
p array2.object_id

puts "Object ids"
array0.each_with_index{|_,i|
  p array0[i].object_id
  p array1[i].object_id
  p array2[i].object_id
  p '--------'
}

The elements inside the array share the same object_id - they are the same object. The arrays have different object ids.

When you a[0].capitalize! you modify an object, which is part in three different arrays.

See also

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