Encapsulation is a core principle of object-oriented programming in Ruby. It involves bundling data and methods that operate on that data within a single unit or object. This concept helps in hiding the internal state of an object from the outside world, promoting data protection and modularity.
In Ruby, encapsulation is achieved through the use of access modifiers and instance variables. By controlling access to an object's internal data, we can ensure that it is manipulated only through well-defined interfaces.
Ruby provides three main access modifiers:
Instance variables in Ruby are always private and can only be accessed directly within the class. They are prefixed with an @ symbol.
Let's look at a simple example of encapsulation in Ruby:
class BankAccount
def initialize(balance)
@balance = balance
end
def deposit(amount)
@balance += amount
end
def withdraw(amount)
if amount <= @balance
@balance -= amount
else
puts "Insufficient funds"
end
end
def balance
@balance
end
private
def log_transaction(type, amount)
puts "#{type}: #{amount}"
end
end
In this example, the @balance
instance variable is encapsulated within the BankAccount
class. It can only be accessed and modified through the public methods deposit
, withdraw
, and balance
.
Ruby provides convenient ways to create getter and setter methods for instance variables. These methods are crucial for maintaining encapsulation while allowing controlled access to object properties.
Here's an example using Ruby's attr_* methods:
class Person
attr_reader :name
attr_accessor :age
def initialize(name, age)
@name = name
@age = age
end
end
person = Person.new("Alice", 30)
puts person.name # Output: Alice
person.age = 31 # Setter method
puts person.age # Output: 31
In this example, attr_reader
creates a getter method for name
, while attr_accessor
creates both getter and setter methods for age
.
By mastering encapsulation, you'll write more robust and maintainable Ruby code. It's a fundamental concept that works hand in hand with other object-oriented principles like inheritance and polymorphism.