What is an Instance Variable in Ruby: Simple Explanation and Example
instance variable is a variable that belongs to a specific object and is accessible only within that object. It is prefixed with @ and stores data unique to each instance of a class.How It Works
Think of an instance variable as a personal notebook that each object carries around. When you create an object from a class, it gets its own notebook to write down information that only belongs to it. This means if you have multiple objects from the same class, each one keeps its own separate notes.
In Ruby, instance variables start with the @ symbol. They live inside the object and can be used by any method within that object to remember or change information. Unlike regular variables, instance variables keep their values as long as the object exists, so you can use them to store the object's state.
Example
This example shows a simple class Person with an instance variable @name. Each person object remembers its own name.
class Person def initialize(name) @name = name # Instance variable end def greet "Hello, my name is #{@name}." end end person1 = Person.new("Alice") person2 = Person.new("Bob") puts person1.greet puts person2.greet
When to Use
Use instance variables when you want each object to keep track of its own data. For example, in a game, each player object can store its own score using instance variables. In a shopping app, each product object can remember its price and name.
Instance variables are perfect when you need to store information that belongs to an object and should not be shared with other objects. They help keep data organized and tied to the right object.
Key Points
- Instance variables start with
@and belong to a single object. - They keep data unique to each object instance.
- Accessible only inside the object’s methods.
- Used to store the state or properties of an object.