Ruby Variable Scope

Phase 0, week 6 - June 23rd, 2014

Ruby has four types of variables: local, global, instance and class.

These variables are represented in different ways and they are accesible in different parts of the code. Let's go through each of them below.

Local Variables

Local variables can start with any lower case letter or an underline and can be accessed only in the code construct they were defined in. So if you create a variable inside a if or while loop, or inside a method or class, that local variable will only be recognized in thouse places.

local_variable = "This is a local variable"

Global Variables

Global variables always start with a $ sign. When Ruby sees a variable like $thisone, it'll make sure it's available all over the code, to any loop, method, class or any other code construct you may use.

$global = "This is a global variable"

Instance Variables

Instance variables always start with a @ sign and they are accessible only inside the instance of an object. If a class has different objects, changing a instance variable will only change it in that instance. Other objects of that class will have local copies of the values and won't be affected.

@instance_variable = "This is a instance variable"

Class Variables

Class variables start with @@ and they are accessible in all instances of a class, so updating it's value in one object of a class will update it in all the other instances. A class variable could be seen as a global variable, but only inside a class.

@class_variable = "This is a class variable"

Pseudo Variables

Ruby also has two pseudo-variables that can not be assigned values. These are nil, which is assigned automatically to variables that have not yet been initialized, and self, which is a variable that refers to the object a class is currently being applyed to.