Variable Scope

Object Oriented Programming

To understand variable scope, one must understand object orientation. Ruby is an object oriented language, that means that everything is based upon objects that have attributes and can be used for various tasks through methods. You can think of an object as a human and a method as a verb such as run. Just as how you tell a human to run, you can also tell an object to do something via methods.

These Ruby objects are not the same. They can be Integer objects, String objects, Array objects etc. We call these individual objects instancesof a particular class.

What Is Variable Scope?

Variable scope is determining how deep (aka the scope) a variable can be used in context of OOP.

When we devise a method for a particular class, we need to create in context of the class, as seen by the example below.

Here we can see a method being defined within a class string.

Local Variables

First up in variable scope is the local variable. They can only be used within their parent object. In the case below, the local variable varcan only be used within method.

Instance Variables

Instance variables are defined with a @ sign before the variable name. They are specific to each indvidual instance of a class. In the case below, we see that the instance variable @varis different for example1and example2.

Class Variables

Class variables are defined with an @@ sign before the variable name. They are specific to the class itself, so if you change the class variable, it affects all instances of that class. They must be initialized at time of instance creation. Take a look at the example below.

Class variable @@varwas defined as 'hello'for example1. However, after we changed the class variable in example2to 'world', the class variable also changed for example1.

Global Variables

Global variables have the most freedom of all. They are defined with a $ sign before the class name. Since they have the most freedom, they can be created anywhere and changed anywhere in the program. If you take a look at the example below, you can see that global variable $varis defined outside of the class, yet when we call method, it returns the value of the global variable. This can make for troublesome debugging, since you can't narrow down your potential problem within your code.

References

Techotopia Tutorials Point New Circle