March 2009
Intermediate to advanced
194 pages
4h
English
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, ...