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]>

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Fixed my test example, but thats not working on my actual project... thanks
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 stackoverflow.com/q/8206523/1241782
Heh yeah its a multidimensional array. The trick with marshal worked. Thanks again

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.