Variable Scope in Ruby

Created By Sagar Rathi
Date: 11/15/2014

What kinds of variables does Ruby support? Where are they accessible? When would you use them and what makes them different?

Local Variable

Local variables are defined with just the small letters and underscores. Just like the name suggests, local variables are locally available for use. For example if a local variable is defined within a method, or a loop, it can only be accessed within that method / loop. All the following are local variables:-

Global Variable

Global variables are defined with $ sign followed by letter/word/or combination of word separated with underscore.These variables are accessible to all the methods, classes and objects; regardless of where they are defined.

Instance Variable

Instance Variables are defined with @ sign in front of a letter/word or combination of words separated by underscore. Instance variables are the most commonly used ones. Unlike the class variables, two or more different objects within the same class or the class which inherits from another class are allowed to have different values for the instance variables. For example

Class Variable

Class Variables are defined with double @@ signs followed by letter/word/or combination of word separated with underscore. These variables are not so common, these can be accessed within the class its defined in. And once the value changes, the value of this variable hangs throughout.

>