O'Reilly logo

Sams Teach Yourself Ruby in 21 Days by Mark Slagell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Instance Variables

The variables that we've used so far have local scope. We've likened their use to pronouns in common language: They carry their meaning within some area of communication and then lose that meaning. With only local variables, it would be impossible for an object to remember anything.

forgetful = Object.new
def forgetful.store(v)
  contents = v
end
def forgetful.retrieve
  return contents
end
forgetful.store("left wallet on table")
 forgetful.retrieve   # error: "contents" is undefined!

The variable contents has a scope limited to the method in which it appears, so the value stored by the store method is inaccessible when we try to get it back in the retrieve method; we say that it is out of scope. There is in fact no relationship ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required