Skip to Main Content
Learn to Program, 2nd Edition
book

Learn to Program, 2nd Edition

by Chris Pine
March 2009
Intermediate to advanced content levelIntermediate to advanced
194 pages
4h
English
Pragmatic Bookshelf
Content preview from Learn to Program, 2nd Edition

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn to Program, 3rd Edition

Learn to Program, 3rd Edition

Chris Pine
The Book of Ruby

The Book of Ruby

Huw Collingbourne

Publisher Resources

ISBN: 9781680500172Errata