From: Natevw Date: 2006-05-16T08:45:10+09:00 Subject: Re: learn to program 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. > Looks like he's trying to get at the "scope" of variables. I think that his example might be more clearly written with parentheses: [code] 1: def little_pest(tough_var) 2: tough_var = nil 3: puts ' HAHA! I ruined your variable!' 4: end 5: 6: tough_var = ' You can\' t even touch my variable!' 7: little_pest(tough_var) 8: puts tough_var [/code] Pay attention to 'tough_var' through the code, it actually refers to two different variables: 1) in line 1, 'tough_var' is the name given to the one argument (~=input value) that the little_pest function takes. It is a local variable. in line 2, this local variable is set to nil. 2) in line 6, a global variable named 'tough_var' is declared and set to the "You can't touch..." line in line 7, little_pest is called with the value of the global tough_var So when tough_var is set to nil in line 2, all that is being set to nil is the local variable named 'tough_var', not the variable from lines 6-8. To the Ruby interpretter, the code might as well be written as: 1: def little_pest(var1) 2: var1 = nil 3: puts ' HAHA! I ruined your variable!' 4: end 5: 6: var2 = ' You can\' t even touch my variable!' 7: little_pest(var2) 8: puts var2 HTH...I'm just learning Ruby, so maybe somebody could correct the details (passing by value,etc.)....but that's what the author is getting at. -natevw