SHARE:
Uncategorized

Variable Scope

Flatiron School / 23 October 2012

The following is a guest post by Jenya Zueva and originally appeared on her blog. Jenya is currently a student a The Flatiron School. You can learn more about her here, or follow her on twitter here.

There are four main types of variables:

  • $global_variable
  • @@class_variable
  • @instance_variable
  • local_variable (use [a..z] or _ )

Ruby comes with two pseudo-variables nil andself that do not accept values. Nil is assigned to uninitialized variables. Self will always refer to the object currently being executed.

Looks simple, right? It gets somewhat confusing when you try to define the scope of each variable. Even more confusing, when you try to call on a variable that is does not belong to your current scope.

Ruby is always here to help you. defined? variable will show you the what the scope of selected variable.

Debugging

If you run this code, it will give Object(NameError), which means that the variable you are trying to call on is currently out of scope. To solve this error locate where you first introduced the variable and either change its scope or rename the second variable.

Local Variable

local_variable can be declaired and referenced only within given scope (method, loop, etc).

Instance Variable

@instance_variables only belong to the given instance of an object. In an example below, when @instance_variable is changed in some_method, it retains its value when called in some_other_method.

Global Variables

$global_variables are set to access anywhere in the program. It is ruby’s convention NOT to use global variables.

“… global variables? 
They pollute the planet. 
You know who uses global variables? 
PHP”

@aviflombaum twitter.com/aviflombaum/…

Debugging will become a nightmare, if you redefine a global variable somewhere in your program, and then try to call on its original value. Ruby offers us a number of major system variables. Aliases will come handy when working on bigger applications.

SymbolDescription$!latest error message$@location of error$_string last read by gets$.line number last read by interpreter$&string last matched by regexp$~the last regexp match, as an array of subexpressions$nthe nth subexpression in the last match (same as $~[n])$=case-insensitivity flag$/input record separator$output record separator$0the name of the ruby script file$*the command line arguments$$interpreter’s process ID$?exit status of last executed child process

Class Variables

A class variable are defined and availbale only inside that class, meaning that only one variable value exists for all objects represented by that instance within that class. @@variable will be available for reference in any methods that might be defined for that class.

Variables are your friends. Learn them, love them.

Modules as Mixins in Ruby Previous Post How to Get Started Writing Tests With Minitest Next Post