Encapsulation in Ruby: Protecting Data
Introduction to Encapsulation
Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It involves bundling data (attributes) and methods that operate on that data into a single unit known as a class. In Ruby, encapsulation helps protect data and restrict direct access to it, promoting data integrity and security. In this guide, we'll explore encapsulation in Ruby with examples.
Private and Protected Access
Ruby provides access control modifiers, such as private
and protected
, to restrict access to class members. Here's an example:
class BankAccount
def initialize(balance)
@balance = balance
end
def deposit(amount)
@balance += amount
end
def withdraw(amount)
@balance -= amount
end
private
def audit_balance
# This method is private and can't be called from outside the class
puts "Current balance: $#{@balance}"
end
protected
def transfer_funds_to(another_account, amount)
# This method is protected and can be called by subclasses
another_account.deposit(amount)
withdraw(amount)
end
end
In this example, the In this example, the Encapsulation in Ruby helps protect data and control access to class members, promoting data integrity and security. By using access control modifiers like Practice encapsulation in your Ruby programs to become a proficient Ruby developer. For more information, refer to the official Ruby documentation. Happy coding!audit_balance
method is marked as private</code, so it can only be called within the class. The
transfer_funds_to
method is marked as protected</code, allowing it to be used by subclasses.</p>
<h2>Accessing Private and Protected Members</h2>
<p>You can access private and protected members within the class or its subclasses. Here's an example:</p>
<pre>class SavingsAccount < BankAccount
def transfer_to_fixed_deposit(amount)
# Subclasses can access protected members
transfer_funds_to(fixed_deposit, amount)
end
private
def fixed_deposit
# This method is private and can only be called within the subclass
# ...
end
end
SavingsAccount
subclass can access the transfer_funds_to
method, which is marked as protected</code, and also defines its own private method,
fixed_deposit
.
Conclusion
private
and protected
, you can ensure that data is accessed and modified in a controlled and secure manner.