The following program has two variables:
def double_this num |
num_times_2 = num*2 |
puts num.to_s+' doubled is '+num_times_2.to_s |
end |
|
double_this 44 |
44 doubled is 88 |
The variables are num and num_times_2. They both sit inside the method double_this. These (and all the variables you have seen so far) are local variables. This means they live inside the method, and they cannot leave. If you try, you will get an error:
def double_this num |
num_times_2 = num*2 |
puts num.to_s+' doubled is '+num_times_2.to_s |
end |
double_this 44 |
puts num_times_2.to_s |
44 doubled is 88 |
example.rb:6:in `<main>': undefined local variable or method `num_times_2' |
for main:Object (NameError) |
Undefined local variable…. In fact, we did define that local variable, but it isn’t local to where we tried to use it; it’s local to the method, which means it’s local to double_this.
This might seem inconvenient, but it’s actually quite nice. Although it does mean you have no access to variables inside methods, it also means they have no access to your variables and thus can’t screw them up, as the following example shows:
tough_var = 'You can't even touch my variable!' |
|
def little_pest tough_var |
tough_var = nil |
puts 'HAHA! I ruined your variable!' |
end |
|
little_pest tough_var |
puts tough_var |
HAHA! I ruined your variable! |
You can't even touch my variable! |
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.
3.145.166.149