Object Oriented Programming

Variable Scope

July 24, 2015

Developing in the Ruby language means engaging in Object Oriented Programming (OOP). More or less, everything we interact with in Ruby is an object (except for blocs, procs, and lambdas but that's another conversation for another time), and these objects interact with one another via messages. We use variables, which inherit properties from their parent objects (again, another blog for another time), but there are different types of variables that are defined, accessible, and written in their own specific way. The below table is a cheat sheet of the different types of Ruby variables and their scope:

Ruby Variable Scope Cheat-Sheet
Global Variables Class Variables Instance Variables Local Variables Constants Pseudo-Variables
  1. Written with $ ie. $global_variable
  2. Accessible everywhere
  3. Considered dangerous to alter
  1. Written with @@ ie. @@class_variable
  2. Accessible amongst different classes and modules
  3. Value remains the same across different instances of the class
  4. Must be initialized, else have value error
  1. Written with @ ie. @instance_variable
  2. Accessible amongst different classes and modules
  3. Gives the value of each instance of the class
  4. Must be initialized, else gives an nil
  1. begin with a lowercase letter or _ ie. local_variable
  2. Accessible within method, class, module, or def
  3. Gives a single value
  1. begin with a uppercase
  2. Accessible within class or module if defined within class or module, else accessible globally
  3. May not be defined within methods
  4. Assigning a constant that's already initialized produces a warning
  1. Cannot assign values to these variables
  2. Appear as local variables, but behave like constants

And that's pretty much the scope of Ruby variables in a nutshell, enjoy!