Duplicating an array of strings.

Posted by Jon on Stack Overflow See other posts from Stack Overflow or by Jon
Published on 2010-04-05T17:32:53Z Indexed on 2010/04/05 17:43 UTC
Read the original article Hit count: 291

Filed under:
|
|
|
|
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

© Stack Overflow or respective owner

Related posts about ruby

Related posts about arrays