Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to duplicate a multi-dimensional array in Ruby?

I have a 2-dimensional array in Ruby that I want to produce a working duplicate of. Obviously I can't do this;

array=[[3,4],[5,9],[10,2],[11,3]]
temp_array=array

as any modifications I make to temp_array will also be made to array, as I have merely copied the object identifier. I thought I would be able to get around this by simply using;

temp_array=array.dup

but this doesn't work as temp_array is simply an array of object identifiers that get duplicated so I still end up modifying the initial array (if I understand what went wrong when I did this). The solution I found was to do the following;

temp_array=[]
array.each{|sub| temp_array << sub.dup}

This achieves what I want but seems to be an awkward way of solving my problem.

I am concerned about how this would work if I didn't know what my array was going to be containing (e.g. if it was possible that some parts of the array had 3-dimensions). I would potentially have to test the class of each member of the array to see if it had to be iterated over in order to duplicate it. Not an impossible task at all, but it seems messy to me. Is this simply a consequence of Ruby lacking built-in support for multidimensional arrays or is there a simple built-in function to do this that I have missed?

like image 372
brad Avatar asked Jan 11 '10 00:01

brad


1 Answers

Here's the "Ruby-esque" way to handle it:

temp_array = Marshal.load(Marshal.dump(your_array_to_be_cloned))

like image 169
Isaac Avatar answered Oct 10 '22 05:10

Isaac