How to Use Instance Variables in Ruby: Simple Guide
In Ruby, an
instance variable starts with @ and belongs to an object, storing data unique to that object. You use it inside instance methods to keep track of object-specific information accessible across instance methods.Syntax
An instance variable in Ruby is written with an @ prefix followed by the variable name. It is used inside instance methods to hold data specific to each object instance.
@variable_name: Defines or accesses an instance variable.- Used inside instance methods to store or retrieve object-specific data.
ruby
class Person def initialize(name) @name = name # instance variable end def greet "Hello, my name is #{@name}." end end
Example
This example shows how to set and use an instance variable @name inside a Ruby class. Each object stores its own name, and the greet method uses that instance variable to return a personalized message.
ruby
class Person def initialize(name) @name = name end def greet "Hello, my name is #{@name}." end end person1 = Person.new("Alice") person2 = Person.new("Bob") puts person1.greet puts person2.greet
Output
Hello, my name is Alice.
Hello, my name is Bob.
Common Pitfalls
One common mistake is trying to access an instance variable outside the object or before it is set, which returns nil. Another is confusing instance variables with local variables (no @), which are limited to the method scope.
Always use @ to refer to instance variables inside instance methods.
ruby
class Person def initialize(name) name = name # wrong: local variable, not instance variable end def greet "Hello, my name is #{name}." # error: 'name' undefined here end end # Correct way: class Person def initialize(name) @name = name # instance variable end def greet "Hello, my name is #{@name}." end end
Quick Reference
@variable: Instance variable, unique to each object.- Defined inside instance methods like
initialize. - Accessible by all instance methods of the object.
- Not accessible directly outside the object.
Key Takeaways
Instance variables start with @ and store data unique to each object.
Use instance variables inside instance methods to keep object-specific state.
Do not confuse instance variables with local variables; always use @ for instance variables.
Instance variables are accessible across instance methods but not outside the object.
Initialize instance variables typically in the initialize method for each object.