Method clear wiping out other array?

Hello all,

Need help.
See code below. The array arr2 has data to start with.
The first 2 puts show output - no problem - both the same as expected.

The last 2 puts - no output - nothing - nada.

Between the lines shown here there is no other code - this is exactly
what the actual code looks like.

puts " #{arr2}"
arr1 = arr2
puts " #{arr1}"

arr2.clear
puts " #{arr1}"
puts " #{arr2}"

Both variables point to the same array.

If you want two arrays, you need to call #dup:

arr2 = arr1.dup


Avdi G.

Avdi,
Thanks. I’ll look into it. To me they should be two separate objects so
I would not expect the two names to refer to the same array.

In the meantime a did a work-around.
I created an empty array “dummy” so
arr2=dummy INSTEAD of arr2.clear.
It worked very well - solved the problem.

Avdi G. wrote in post #1068667:

Both variables point to the same array.

If you want two arrays, you need to call #dup:

arr2 = arr1.dup


Avdi G.
http://avdi.org

On Jul 13, 2012, at 23:31 , Mike O. wrote:

Thanks. I’ll look into it. To me they should be two separate objects so
I would not expect the two names to refer to the same array.

variables are not objects. variables are names given to references to
objects. After var2=var1 you had this setup:

var1 --> ±----+
| obj |
var2 --> ±----+

Ryan D. wrote in post #1068678:

On Jul 13, 2012, at 23:31 , Mike O. wrote:

Thanks. I’ll look into it. To me they should be two separate objects so
I would not expect the two names to refer to the same array.

variables are not objects. variables are names given to references to
objects. After var2=var1 you had this setup:

var1 --> ±----+
| obj |
var2 --> ±----+

Ryan,
Thanks. So the assignment is actually a pointing/reference operation
rather than a copy operation.
As such the assigment caused me to lose all reference to the other array
object.
I came up with a work-around, and now my code works well.
Thanks again.

On Sat, Jul 14, 2012 at 10:31 AM, Mike O. [email protected]
wrote:

I came up with a work-around, and now my code works well.

You don’t need a “work-around”, you need to learn the language :slight_smile:

As Avdi pointed out, your use case calls for the #dup method.