arr = ["red","green","yellow"]
arr2 = arr.clone
arr2[0].replace("blue")
puts arr.inspect
puts arr2.inspect
produces:
["blue", "green", "yellow"]
["blue", "green", "yellow"]
Is there anyway to do a deep copy of an array of strings, other than using Marshal as i understand that is a hack.
I could do:
arr2 = []
arr.each do |e|
arr2 << e.clone
end
but it doesn't seem very elegant, or efficient.
Thanks
I recommend your initial idea, but written slightly more concisely:
Your second solution can be shortened to
arr2 = arr.map do |e| e.dup end
(unless you actually need the behaviour ofclone
, it's recommended to usedup
instead).Other than that your two solutions are basically the standard solutions to perform a deep copy (though the second version is only one-level deep (i.e. if you use it on an array of arrays of strings, you can still mutate the strings)). There isn't really a nicer way.
Edit: Here's a recursive deep_dup method that works with arbitrarily nested arrays:
You might also want to define deep_dup for other containers (like Hash), otherwise you'll still get a shallow copy for those.
You can make a deep copy of array
a
by following code:You can use this hack:
But it is just for fun :)
And it will work only for 1 level arrays
It looks so simple.. Just run the below code:
Run above code and you will notice the difference. Cheers !
I am in a similar situation and very concerned about speed. The fastest way for me was to make use of
map{&:clone}
So try this: