There are four different types of variables in Ruby- Local variables, Instance variables, Class variables and Global variables. An instance variable in ruby has a name starting with @ symbol, and its content is restricted to whatever the object itself refers to. Two separate objects, even though they belong to the same class, are allowed to have different values for their instance variables.
These are some of the characteristics of Instance variables in Ruby:
- Instance variable have the value nil before initialization.
- All instance variables are private by default.
- The instance variables of an object can only be accessed by the instance methods of that object.
- The ruby instance variables do not need a declaration. This implies a flexible object structure.
- Every instance variable is dynamically appended to an object when it is first referenced.
- An instance variable belongs to the object itself (each object has its own instance variable of that particular class)
- One instance object can alter the values of its instance variables without modifying any other instance.
- An Instance variable can be used by several class methods except when the method is considered to be static.
Geek name is R2J
In the above program, geekName is the instance variable initialized using a constructor and is accessed by the instance method displayDetails() of the class Geek.
Let’s look at another program to illustrate the use of instance variables in Ruby:
Geek age is 20 Geek age is 21
In the above program, geekAge is the instance variable initialized in the instance method getAge(), here geekAge is also accessed by other two instance methods incrementAge() and displayDetails() in which incrementAge() method modifies the value of geekAge and displayDetails() is used to display the value of geekAge.
- Ruby | Types of Variables
- Ruby | Pre-define Variables & Constants
- Ruby | Class Method and Variables
- How to create a Struct Instance Using a Struct Literal in Golang?
- Difference between Schema and Instance in DBMS
- Python Variables
- How to pass PHP Variables by reference ?
- CSS | Variables
- Perl | Variables
- Difference between static and non-static variables in Java
- How to avoid Compile Error while defining Variables
- GRE Data Analysis | Distribution of Data, Random Variables, and Probability Distributions
- ES6 | Variables
- Special variables in Perl
- How to pass form variables from one page to other page in PHP ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.