From: Logan Capaldo Date: 2006-05-16T08:29:30+09:00 Subject: Re: learn to program On May 15, 2006, at 6:05 PM, corey konrad wrote: > I realy dont understand what Chris is talking about here in his book > "learning to program" Can someoe shed some light on this > > def little_pest tough_var > tough_var = nil > puts ' HAHA! I ruined your variable!' > end > > tough_var = ' You can\' t even touch my variable!' > little_pest tough_var > puts tough_var > > output: > HAHA! I ruined your variable! > You can' t even touch my variable! > > excerpt from his book: > In fact, two variables in that little program are named tough_var: > one inside little_pest and one outside of it. They don�t communicate. > They aren�t related. They aren�t even friends. When we called > little_pest tough_var, we really just passed the string from one > tough_var to the other (via the method call, the only way they can > even > sort of communicate) so that both were pointing to the same string. > Then little_pest pointed its own local tough_var to nil, but that > did nothing to the tough_var variable outside the method. > > -- > Posted via http://www.ruby-forum.com/. > It has to do with variable scoping. Try this metaphor on for size. You have a stack of papers. When ever you call a function, you grab a blank piece of paper. On it, you write the names and values for all the variables in that function and you put it on top of the stack. You then execute the code inside the function. Any code in the function can only change the stuff written on the piece of paper at the top of the stack. When the function finishes, we take it's piece of paper off the top of the stack of papers and throw it away. Ok so we have an initial piece of paper. We write on it: tough_var = ' You can\' t even touch my variable!' then we call a function, little_pest. We grab a blank piece of paper for little pest, and write on it tough_var = ' You can\'t even touch my variable!' we put it on top of the stack. Then little_pest says to set tough_var to nil. We look at our piece of paper on the top of the stack of papers, scribble out tough_var and write tough_var = nil We then print the "HAHA!" message, and finish our function. Since we are done with our function, we take the piece paper off the top of the stack, crumple it up, and throw it away. then we saee we must print tough_var. We look at the paaper on the top of the stack to see what tough var means. Oh its a string with ' You can\'t touch my variable '. Ok, we print that.