PDA

View Full Version : question about array append function and possibly scope


kpeng1
July 3rd, 2006, 12:40 PM
Hi,

The problem I am having is that I have a class that I define two class variables in. After setting one of the class variable myVar2, I append the results to my second variable myVar1. Afterwards, I clear the contents of myVar2 by using the .clear function, but the problem is that when I print the contents of myVar2 I do not see the contents that I have appended with myVar2. Does the << operator only appends a pointer or something and it does not append the entire content? Is there another operator or is this possibly some kind of scoping issue?

My code is show below. The addtoVar2 is always called before addtoVar1 is called.

class myClass
@@myVar1 =[]
@@myVar2 = []

def addtoVar1
@@myVar1 << "x, y" << @@myVar2
@@myVar2.clear
pp @@myVar1 # result is [x, y, []] not [x, y, [a, b, c, d]] why?
end

def addtoVar2
localVar = "a, b, c , d"
@@myVar2 << localVar
end

end

rob
July 3rd, 2006, 04:28 PM
The << method will append item(s) to an array just like you are proposing, but in the specific example you have, I don't see any way for the myVar2 to get propigated, except if you call addToVar2.

Also, you realize you're sending strings to the array like "x, y", and not 2 numbers or variables when you surround them in quotes, right? I'm not sure if this is for our example or this is your real code. This doesn't make a difference if you want to store an array of strings, but I just wanted to clarify that.

Can you paste your implimentation code so we can see the entire process? The devil of this may be in the code using the object instance and not in the class itself.

kpeng1
July 3rd, 2006, 05:02 PM
Well this code is for implementing a GUI. So each of those fucntion corresponds to a button being pressed. There is error checking that occurs to make sure that addtovar2 function is always called before addtovar1 so myVar2 always get propagated, I have checked it. The problem is that after I append myVar2 to myVar1 and print it is ok I see all the elements, but right after I call myVar2.clear and print the contents of myVar1 I get an empty element in place where I appended myVar2.

kpeng1
July 5th, 2006, 12:55 PM
So I fixed the problem. What I had to do was add a .dup when appending myVar2 so I have this line @@myVar1 << "x, y" << @@myVar2.dup.

Now I have another question and that is why I would need to do that. Does ruby append everything by reference, so if I have say a local variable and I am appending it to a global variable and the local variable goes out of scope will the appended value be seen in the global variable? or do I need to add the .dup in the local variable to duplicate it first.