Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Adding an element to a copy of an array

0 views
Skip to first unread message

Jim Burgess

unread,
Jul 29, 2010, 10:36:39 AM7/29/10
to
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/.

Jim Burgess

unread,
Jul 29, 2010, 10:42:13 AM7/29/10
to
Answered my own question.
Array.dup ist the way to go.

Joseph E. Savard

unread,
Jul 29, 2010, 10:47:45 AM7/29/10
to
array = ["one", "two", "three"]
array_copy = array.clone

array_copy << "four"
p array
p array_copy

output:

["one", "two", "three"]
["one", "two", "three", "four"]
0 new messages