content of an array gets cleared

P

Parv G.

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
 
R

Ragav Satish

Parv said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,200
Messages
2,571,046
Members
47,646
Latest member
xayaci5906

Latest Threads

Top