2

I have a class that contains an array. This is an example class. a is an array

class Holder
  attr_accessor :a
end

I am trying to make a copy of an object and execute a function on its array. An example situation:

t = Holder.new
t.a = (1..9).to_a
t2= Holder.new
t2.a = t.a
t2.a[2]+=10
t2.a
# => [1, 2, 13, 4, 5, 6, 7, 8, 9]
t.a
# => [1, 2, 13, 4, 5, 6, 7, 8, 9]

Both array in each object are effected. I don't know how to make them separate. I tried with clone and dup too.

dupt = t2.dup
dupt.a[8]+=10
dupt
# => #<Holder:0x007fb6e193b0a8 @a=[1, 2, 13, 4, 5, 6, 7, 8, 19]>
t2
# => #<Holder:0x007fb6e1962ba8 @a=[1, 2, 13, 4, 5, 6, 7, 8, 19]>
sawa
  • 165,429
  • 45
  • 277
  • 381
Matthew
  • 432
  • 4
  • 17

1 Answers1

2

You need to call dup on the Array, not on your Holder object. dup will not create copies of all the sub-elements in the object you are trying to copy.

t2.a = t.a.dup
Mike S
  • 11,329
  • 6
  • 41
  • 76
  • Fixed my test example, but thats not working on my actual project... thanks – Matthew Aug 21 '15 at 00:01
  • In your actual project are there more elements inside of the `Array` that might need their own `dup` call? If so you will need a deep copy solution so that you don't have to call `dup` on every object manually. This might help http://stackoverflow.com/q/8206523/1241782 – Mike S Aug 21 '15 at 00:04
  • Heh yeah its a multidimensional array. The trick with marshal worked. Thanks again – Matthew Aug 21 '15 at 00:29