There are few types of variables that can be defined in Ruby
- Local Variables
- Global Variables
- Class Variables
- Instance Variables
- Ruby Constants
Local variable begin with a lowercase letter or an ‘_’. The scope of a local variable can be limited to a class, a module, a function or even a block of code.
All the uninitialized local variables are interpreted as a call to a method that has no arguments. When a value is assigned to such a variable, it is said to have been initialized. These variables exist till the end of the scope is reached.
Global Variables are declared with a $ sign. The scope of these variables spans through the entire program. An uninitialised global variable will end up having a nil value.
Class variables start with a @@ sign. They need to be initialized before being used. The value of the class variable remains consistent throughout the class. If the value of the class variable changes in an instance, then the value is perceived to be changed in all the other instances.
Instance variables start with an @ sign. These variables will have a nil value if they are not initialized. The scope of these variables is restricted to whatever object self refers to.
They are variables that have the scope and the appearance of a local variable but cannot be assigned any value.
self − The receiver object of the current method.
true − Value representing true.
false − Value representing false.
nil − Value representing undefined.
__FILE__ − The name of the current source file.
__LINE__ − The current line number in the source file.
Ruby constants are defined with an uppercase letter in the beginning. The scope of these constants is dependent on the place they have been defined and initialized at.
One has to be careful while working with constants and take care of the following pointers
- Constants should not be defined within methods
- Referencing uninitialized constant throws an error
- Assigning a value to an initialized constant shows a warning.