How to Use Instance Variables in Ruby

RubyServer Side ProgrammingProgramming

In Ruby, there are four different types of variables that we can declare −

  • Local Variables

  • Instance Variables

  • Class Variables

  • Global Variables

An Instance variable has a name that starts with the @ symbol. It should be noted that the contents of an instance variable are only restricted to the object which itself refers to.

An important point to note about the instance variable in Ruby is that, even if we have two separate objects that belong to the same class, we are allowed to have different values for their instance variables.

Instance Variable Characteristics in Ruby

Before checking how to use instance variables in Ruby, let's understand some of their important characteristics −

  • An object's instance variables can only be accessed via its instance methods.

  • There is no need to declare Ruby instance variables. Therefore, the object structure is flexible.

  • When an object is referenced for the first time, every instance variable is dynamically added.

  • If an instance object changes its instance variables, no other instance is affected.

  • Before initialization, instance variables have nil values.

  • By default, instance variables are private.

Example 1

Now let's consider a very basic example where we declare an instance variable in Ruby, and then use another method to print that instance variable.

class First_Class

   # constructor
   def initialize()
      # instance variable
      @Name = "Mukul"
   end

   # defining method display
   def display()
      puts "Student Name is #@Name"
   end
end

# creating an object of First_Class
obj = First_Class.new()

# calling the instance methods of First_Class
obj.display()

In the above code, we have created a class named First_Class that contains a method to initialize (a constructor) and another method to display() and then we are creating an object of the class and finally calling the display method on that class.

Output

It will produce the following output.

Student Name is Mukul

Example 2

Now, let's create another method to create another instance variable and then use one more method as a setter of that instance variable. Consider the code shown below.

class First_Class
   # constructor
   def initialize()
      # instance variable
      @Name = "Mukul"
   end

   def appendName()
      @Name += " Latiyan"
   end

   # defining method display
   def display()
      puts "Student's name is #@Name"
   end
end

# creating an object of class Tuts
obj = First_Class.new()

# calling the appendName method
obj.appendName()

# calling the display method
obj.display()

Output

It will produce the following output.

Student's name is Mukul Latiyan
raja
Updated on 12-Apr-2022 08:52:45

Advertisements