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

Instance Variables

Normally when we want to talk about a string, we will just call it a string. However, we could also call it a string object. Sometimes programmers might call it an instance of the class String, but it’s just another way of saying string. An instance of a class is just an object of that class.

So, instance variables are just an object’s variables. A method’s local variables last until the method is finished. An object’s instance variables, on the other hand, will last as long as the object does. To tell instance variables from local variables, they have @ in front of their names:

class​ Die
def​ roll
@number_showing = 1 + rand(6)
end
def​ showing
@number_showing
end
end
die = Die.new
die.roll
puts die.showing
puts die.showing ...
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