Chapter 5. The default object (self), scope, and visibility

 

This chapter covers

  • The role of the current or default self object
  • Scoping rules for local, global, and class variables
  • Constant lookup and visibility
  • Method-access rules

In describing and discussing computer programs, we often use spatial and, sometimes, human metaphors. We talk about being “in” a class definition or returning “from” a method call. We address objects in the second person, as in obj.respond_to?("x") (that is, “Hey obj, do you respond to 'x'?”). We use these metaphors to describe the context of the program at any given point. Context is important when discerning the value of an identifier or the state of an object. As a program runs, its context constantly shifts. Most words and tokens—most identifiers—can mean different things at different places and times.

This chapter is about orienting yourself in Ruby code: knowing how the identifiers you’re using are going to resolve, following the shifts in context, and making sense of the use and reuse of identifiers and terms. If you understand what can change from one context to another, and also what triggers a change in context (for example, entering a method-definition block), you can always get your bearings in a Ruby program. And it’s not just a matter of passive Ruby literacy: you also need to know about contexts and how they affect the meaning of what you’re doing when you’re writing Ruby.

5.1. Understanding self, the current/default object

5.2. Determining scope

5.3. Deploying method-access rules

5.4. Writing and using top-level methods

Summary

sitemap