0
0
Rubyprogramming~5 mins

Instance variables (@) in Ruby

Choose your learning style9 modes available
Introduction

Instance variables store information unique to each object. They keep data safe inside the object.

When you want each object to remember its own details, like a person's name or age.
When you need to keep track of an object's state across different methods.
When you want to avoid sharing data between different objects of the same class.
When you want to organize data inside an object clearly and safely.
Syntax
Ruby
@variable_name = value

Instance variables always start with the @ symbol.

They belong to the object, not the class itself.

Examples
This sets an instance variable @name when creating a new Person.
Ruby
class Person
  def initialize(name)
    @name = name
  end
end
This method stores the age in an instance variable @age.
Ruby
def set_age(age)
  @age = age
end
This method returns the value stored in the instance variable @name.
Ruby
def get_name
  @name
end
Sample Program

This program creates a Dog object with a name and breed stored in instance variables. Then it prints the dog's details.

Ruby
class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  def info
    "Dog's name is #{@name} and breed is #{@breed}."
  end
end

my_dog = Dog.new("Buddy", "Golden Retriever")
puts my_dog.info
OutputSuccess
Important Notes

Instance variables are private to the object. You cannot access them directly from outside without methods.

Each object has its own copy of instance variables, so changing one object's variable does not affect others.

Summary

Instance variables store data unique to each object.

They always start with @.

Use methods to read or change instance variables safely.