[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

content of an array gets cleared

Parv G.

10/4/2008 3:53:00 AM

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
--
Posted via http://www.ruby-....

2 Answers

ragav

10/4/2008 4:06:00 AM

0

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
--
Posted via http://www.ruby-....

Parv G.

10/4/2008 4:15:00 AM

0


> tempArray = array.dup #=> make a shallow copy.
> array.clear
> puts tempArray.length #=> 5


That should do the trick for me.

Thanks a lot!
Parv
--
Posted via http://www.ruby-....