Instance variables are a fundamental concept in Ruby's object-oriented programming paradigm. They allow objects to maintain their own state, storing data that is unique to each instance of a class.
In Ruby, instance variables are prefixed with an "@" symbol. They are accessible throughout an object's methods and have a lifespan equal to that of the object itself. Unlike local variables, instance variables persist across method calls within the same object.
To define an instance variable, simply use the "@" prefix followed by the variable name:
@variable_name = value
Instance variables are typically initialized in the constructor method (initialize
) of a class:
class Person
def initialize(name, age)
@name = name
@age = age
end
end
By default, instance variables are private to the object. To access them from outside the object, you need to define getter and setter methods. Ruby provides several ways to do this:
class Person
def name
@name
end
def name=(new_name)
@name = new_name
end
end
Ruby offers convenient shorthand methods for creating getters and setters:
class Person
attr_reader :name # Creates a getter
attr_writer :age # Creates a setter
attr_accessor :email # Creates both getter and setter
end
initialize
methodLet's create a simple BankAccount
class to demonstrate instance variables:
class BankAccount
attr_reader :balance
def initialize(initial_balance = 0)
@balance = initial_balance
end
def deposit(amount)
@balance += amount
end
def withdraw(amount)
if amount <= @balance
@balance -= amount
else
puts "Insufficient funds"
end
end
end
# Usage
account = BankAccount.new(1000)
puts account.balance # Output: 1000
account.deposit(500)
puts account.balance # Output: 1500
account.withdraw(200)
puts account.balance # Output: 1300
In this example, @balance
is an instance variable that maintains the current balance of each BankAccount
object. The deposit
and withdraw
methods manipulate this instance variable, allowing each account to maintain its own state.
Instance variables are crucial for implementing object-oriented designs in Ruby. They enable objects to maintain their own state, promoting encapsulation and data integrity. By mastering instance variables, you'll be able to create more robust and flexible Ruby programs.