author avatar

syedsibtain

Fri Apr 26 2024

In Ruby, instance variables are variables that belong to a specific instance of a class. They are prefixed with the @ symbol and are accessible within the instance methods of that class. Instance variables allow objects to maintain state and store information unique to each instance. Example:

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end

  def say_intro
    puts "Hello, my name is #{@name} and I am #{@age} years old"
  end
end

# Create a new instance of Person
person1 = Person.new("John", 18)

# Call the say_intro method
person1.say_intro

In this example, @name is an instance variable of the Person class, representing the name of each Person object created. The initialize method is a constructor that sets the value of @name when a new Person object is created. The say_intro method uses the instance variable @name to give the intro of the person with their name and age when called.

#ruby