Forum: Ruby content of an array gets cleared

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
520d0b178a769fdffe5cd42b7132cdcc?d=identicon&s=25 Parv G. (parvg)
on 2008-10-04 05:54
Hello,

Looking for you suggestions.

1. array = %w(a b c d e)
2. tempArray = array
3. array.clear
4. puts tempArray.length

line 4 outputs: 0
Why does my tempArray get cleared also?
Any suggestions on how to keep the tempArray content from clearing out?

Thanks
Fc8263f8baca7a7b76605cfdd0c4afa2?d=identicon&s=25 Ragav Satish (ragav)
on 2008-10-04 06:07
Parv G. wrote:
> Hello,
>
> Looking for you suggestions.
>
> 1. array = %w(a b c d e)
> 2. tempArray = array
> 3. array.clear
> 4. puts tempArray.length
>
> line 4 outputs: 0
> Why does my tempArray get cleared also?
> Any suggestions on how to keep the tempArray content from clearing out?
>
> Thanks

because array and tempArray are references to the same Array instance.

# see same object
array.object_id     #=> -605829518
tempArray.object_id #=> -605829518

tempArray = array.dup #=> make a shallow copy.
array.clear
puts tempArray.length #=> 5
520d0b178a769fdffe5cd42b7132cdcc?d=identicon&s=25 Parv G. (parvg)
on 2008-10-04 06:16
> tempArray = array.dup #=> make a shallow copy.
> array.clear
> puts tempArray.length #=> 5


That should do the trick for me.

Thanks a lot!
Parv
This topic is locked and can not be replied to.