tTypes Of Variables In Ruby
There are five types of variables in ruby all of them are discussed below:-
| Variable Scope | Name Begin With |
|---|---|
| 1} Constants Variable | [ A - Z ] |
| 2} Local Variable | [ a - z ] or _(underscore) |
| 3} Global Variable | $ ( Doller ) |
| 4} Instance Variable | @ (at) |
| 5} Class Variable | @@ ( double at ) |
we will look at all those one by one.
Constant Variable:-
This is the only Language that allows a constant value to changed value under the execution. The name of these variables is in all capital letters.
Example:-
CONSTANT = "hello"
Ruby Local Variable:-
Local variables are local to the code construct in which they are declared. For example, a local variable declared in a method or within a loop cannot be accessed outside of that loop or method. These variable names start with small letters and underscore.
Example:-
a) test_num = 2
b) _test = "hello world"
Ruby Global Variable:-
Global variables in ruby are accessible from anywhere in the ruby program, regardless of where they are declared. Global variable names are prefixed with a dollar sign($).The use of global variables is strongly discouraged. The problem with global variable is that, not only are they visible anywhere in the code for a program, they can also be changed from anywhere in the application, This can make tracking bugs difficult.
Ruby Class Variable:-
A class variable that is shared amongst all instances of a class. This means that only one variable value exists for all objects instantiated from this class. This means that if one object instance changes the value of the variable, that new value will essentially be changed in all instances.
Ruby Instance Variable:-
An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to. ... Instance variables of ruby do not need declaration. This implies a flexible structure of objects. In fact, each instance variable is dynamically appended to an object when it is first referenced. check hereExample:-
a) @ test_num = 2
b) @test = "hello world"
Comments
Post a Comment