Adding an element to a copy of an array

Hi,

array = ["one", "two", "three"]
array_copy = array
array_copy << "four"
p array
p array_copy

#=>
["one", "two", "three", "four"]
["one", "two", "three", "four"]

How can I add an element to "array_copy" and leave "array" unaltered?

Cheers.

···

--
Posted via http://www.ruby-forum.com/.

Answered my own question.
Array.dup ist the way to go.

···

--
Posted via http://www.ruby-forum.com/.

array = ["one", "two", "three"]
array_copy = array.clone
array_copy << "four"
p array
p array_copy

output:
["one", "two", "three"]
["one", "two", "three", "four"]

···

From: Jim Burgess <jack.zelig@gmail.com>
Reply-To: <ruby-talk@ruby-lang.org>
Newsgroups: comp.lang.ruby
Date: Thu, 29 Jul 2010 23:36:39 +0900
To: ruby-talk ML <ruby-talk@ruby-lang.org>
Subject: Adding an element to a copy of an array

Hi,

array = ["one", "two", "three"]
array_copy = array
array_copy << "four"
p array
p array_copy

#=>
["one", "two", "three", "four"]
["one", "two", "three", "four"]

How can I add an element to "array_copy" and leave "array" unaltered?

Cheers.
--
Posted via http://www.ruby-forum.com/\.