Ruby - Instance Variables

1. Introduction

In Ruby, instance variables are utilized to store object-specific data. These variables are prefixed with an @ symbol and are accessible throughout an object's instance. This guide dives into the concept of instance variables in Ruby and illustrates their use.

Definition

Instance variables in Ruby are variables that begin with the @ character. They hold values that are specific to each object (or instance) of a class, allowing individual objects to have distinct values for these variables.

2. Program Steps

1. Define a class.

2. Inside the class, initialize instance variables using methods or the special initialize method.

3. Instantiate objects of the class.

4. Access and manipulate the instance variables using methods.

3. Code Program

# Define the class
class Book
  # Initialize method to set the title and author of the book
  def initialize(title, author)
    @title = title
    @author = author
  end
  # Method to retrieve the book's title
  def title
    @title
  end
  # Method to retrieve the book's author
  def author
    @author
  end
  # Method to display book details
  def display
    puts "The book titled '#{@title}' is authored by #{@author}."
  end
end
# Create an instance of the Book class
my_book = Book.new("The Ruby Way", "Hal Fulton")
# Call the display method on the book object
my_book.display

Output:

The book titled 'The Ruby Way' is authored by Hal Fulton.

Explanation:

1. We start by defining a Book class.

2. Inside the Book class, we define an initialize method that accepts two parameters: title and author. This method sets the instance variables @title and @author.

3. Getter methods, title and author, are then defined to retrieve the respective instance variable values.

4. The display method prints out a message containing the values of the @title and @author instance variables.

5. We instantiate an object of the Book class using Book.new and pass the title and author of the book as arguments. This object is assigned to the my_book variable.

6. Lastly, we call the display method on the my_book object, which displays the output message.

Instance variables allow each object to maintain its unique state, ensuring that data stored in one object doesn't interfere with the data in another.


Comments