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}
end
end
class Object
def deep_dup
dup
end
end
class 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
end
end
You might also want to define deep_dup for other containers (like Hash), otherwise you'll still get a shallow copy for those.