Variable Scope and Access in Ruby: The Important Parts

What is Variable Scope? How about Name Resolution?

  1. What is the “scope” of a variable? Where is a given variable accessible in a program?
  2. What is “in scope” at a particular point in a program? What are the visible variables, methods, and classes currently accessible?
  1. What is in scope (can an accessible variable be found?)
  2. When the resolution occurs

Scope and Name Resolution: A Visualization

  • Available local variables
  • Receiver or “calling object” (the value of self)
Photo by Marc Sendra Martorell on Unsplash

Why Does Scope Matter?

  1. Naming: Without scope, we’d have to name everything uniquely, or else Ruby wouldn’t know which variable/method/class to resolve to. With scope, variables of the same name can exist across a program without experiencing name collisions.
  2. Data Protection and Security: Scope restricts accidental or intentional access of variables in different parts of a program.
  3. Object-Oriented Programming: Scope is foundational to OOP’s encapsulating wonders. Without scope boundaries, encapsulation would be impossible. In fact, OOP introduces variable types (instance and class variables) with specific scoping rules designed to encapsulate state. For those in RB120: if the primary mechanism for encapsulating methods is method access control, we can think of scope as variable access control.

How does Ruby Set a Variable’s Scope?

  1. The variable’s type: is it a local_variable, @instance_variable, @@class_variable, CONSTANT, or $global_variable?
  2. The execution context (binding) of the program when the variable is initialized: you (the program) can add new variables into the bubbles you currently reside in. Local, class and instance variables use this criterion to determine their scope.
  3. The mere structure of the code surrounding the variable where it is initialized. This sounds similar to the previous point but is subtly different. This type of scope depends solely on location. The program doesn’t even need to run to evaluate variables’ scope like this; it can be figured out beforehand. A variable scoped in this way is said to have pure lexical scope. Constants use this criterion to determine their scope.

Scoping and Resolution: From the Variable’s Perspective

Local Variables

  • Scope: The class/module definition, method, or block in which it is initialized; local variables have the most narrow scope out of all variable types.
  • Resolution: Given a name with all lowercase characters, the current binding is searched for both local variables and methods (think binding.local_variables).

Instance Variables

  • Scope: In Ruby, all code executes in the context of some calling object, otherwise known as the “receiver”. Every method call has some receiver: the receiver of an instance method is either explicitly defined: receiver.method; otherwise, it is implied — the receiver of method without anything prepended is self. The point is that when any method is invoked, a specific calling object is executing. If an instance variable is initialized under an object’s execution, it is scoped to that object.
  • Resolution: A name prepended with @ signals Ruby to search for an instance variable in the scope of the currently executing object: which can be thought of as self or binding.receiver.

Class Variables

  • Scope: Class variables can be thought of as global variables in the context of classes. A class variable initialized anywhere in a class definition has a scope that includes the class in which it’s defined, any instances of that class, any subclasses of that class, and any instances of those subclasses — a pretty wide scope indeed.
  • Resolution: A name prepended with @@ will search for a class variable in class-level scope. Because of their broad scoping rules, only one shared copy of a class variable with some name can exist among a class and all its subclasses. Therefore, if @@class_variable is initialized in a superclass, references to it in any subclasses will resolve to the same variable.

Constants (Constant Variables)

  • Scope: Technically, constants are accessible anywhere. Paradoxically, this does not mean their scope is everywhere. A constant’s scope only consists of the lexical (positional) scope in which it is declared — the enclosing module or class definition. Constants are accessible from outside their scope using a namespacing resolution technique discussed below.
  • Resolution: Unlike other variables, constants are resolved before runtime, before any notion of an “execution context”. This might seem strange, but Ruby achieves this with a step-by-step procedure after scanning for constant references (any name beginning with an uppercase letter). For each reference to a constant that’s needed at runtime, the following sequence of steps takes place:
  1. The immediate lexical scope surrounding the name is searched, starting at the innermost lexical scope moving outwards (excluding the top-level, which is not considered part of the lexical scope).
  2. The inheritance hierarchy of the innermost currently open class/module is searched.
  3. The top-level is searched (any constants defined outside of a class/method definition, at the “top-level”).

Global Variables

Scoping and Name Resolution: From the Program’s Perspective

  1. Scope gates: Keywords that delineate a new scope boundary for local variables only
  2. The currently executing object (the “calling object”): Value of self at a given point

Scope Gates

The Calling Object

In Conclusion: Scope is Complicated




Aspiring software engineer, learning at Launch School

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

TryHackMe - RootMe

Code Comments Are Stupid

So I Wanted To Animate A UIRefreshControl

📔Plans for Axie Infinity Origin

Developer’s new love: Flutter

The Resolutions for a New Year of Vulns

Getting started with Hazelcast on Azure Kubernetes Service ( AKS )

Screenshot of AKS on my Azure portal

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ethan Weiner

Ethan Weiner

Aspiring software engineer, learning at Launch School

More from Medium

What happens when you run a C++ program?

Classes and Instances in Object-Oriented Ruby : A Newbie’s Guide

A Visual Guide to Variables as Pointers and Object Passing, in Ruby

Lessons learnt from publishing my programming course — Preslav Mihaylov