Open In App

Instance Variables in Ruby

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:



Example #1:




# Ruby program to illustrate instance variables using constructor
  
class Geek
  
       # constructor
       def initialize() 
   
         # instance variable     
         @geekName = "R2J"
       end   
  
       # defining method displayDetails
       def displayDetails() 
           puts "Geek name is #@geekName"
       end    
  
end
  
# creating an object of class Geeks
obj=Geek.new()
  
# calling the instance methods of class Geeks
obj.displayDetails()

Output:



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:

Example #2:




# Ruby program to illustrate instance variables using instance methods
   
class Geek
   
       # defining instance method getAge
       def getAge(n)
             
         # instance variable     
         @geekAge = n
       end  
          
       # defining instance method incrementAge
       def incrementAge() 
           @geekAge +=1
       end
   
       # defining instance method displayDetails
       def displayDetails() 
           puts "Geek age is #@geekAge"
       end   
   
end
   
# creating an object of class Geeks
obj = Geek.new
   
# calling the instance methods of class Geeks
obj.getAge(20)
obj.displayDetails()
obj.incrementAge()
obj.displayDetails()

Output:

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.


Article Tags :