Local Variables
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, ...
Get Learn to Program, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.