There are different types of variables in Ruby:
- Local variables
- Instance variables
- Class variables
- Global variables
Each variable in Ruby is declared by using a special character at the start of the variable name which is mentioned in the following table:
| Symbol |
Type of Variable |
| [a-z] or _ |
Local Variable |
| @ |
Instance Variable |
| @@ |
Class Variable |
| $ |
Global Variable |
Local Variables: A local variable name always starts with a
lowercase letter(a-z) or underscore (_). These variables are local to the code construct in which they are declared. A local variable is only accessible within the block of its initialization. Local variables are not available outside the method. There is no need to initialize the local variables.
Example:
age = 10
_Age = 20
Instance Variables: An instance variable name always starts with a
@ sign. They are similar to Class variables but their values are local to specific instances of an object. Instance variables are available across methods for any specified instance or object i.e. instance variables can change from object to object. There is no need to initialize the instance variables and uninitialized instance variable always contains a
nil value.
Example:
Output:
Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
Class Variables: A class variable name always starts with
@@ sign.It is available across different objects. A class variable belongs to the class and it is a characteristic of a class. They need to be initialized before use. Another way of thinking about class variables is as global variables within the context of a single class. A class variable is shared by all the descendants of the class. An uninitialized class variable will result in an error.
Example:
Output:
Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Total number of customers: 1
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala
Total number of customers: 2
Global Variables: A global variable name always starts with
$. Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. Its scope is global, means it can be accessed from anywhere in a program. By default, an uninitialized global variable has a
nil value and its use can cause the programs to be cryptic and complex.
Example:
Output:
Global variable in Class1 is 10
Global variable in Class2 is 10