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 ...
Get Sams Teach Yourself Ruby in 21 Days 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.