Duplicating a Ruby array of strings
Your second solution can be shortened to arr2 = arr.map do |e| e.dup end
(unless you actually need the behaviour of clone
, it's recommended to use dup
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:
class Array def deep_dup map {|x| x.deep_dup} endendclass Object def deep_dup dup endendclass Numeric # We need this because number.dup throws an exception # We also need the same definition for Symbol, TrueClass and FalseClass def deep_dup self endend
You might also want to define deep_dup for other containers (like Hash), otherwise you'll still get a shallow copy for those.
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:
pry(main)> a = (10000..1000000).to_a.shuffle.map(&:to_s)pry(main)> Benchmark.ms { b = a.deep_dup } => 660.7760030310601pry(main)> Benchmark.ms { b = a.join("--!--").split("--!--") }=> 605.0828141160309pry(main)> Benchmark.ms { b = a.map(&:clone) }=> 450.8283680770546