0
0
Rubyprogramming~30 mins

Protected and private visibility in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Protected and Private Visibility in Ruby
📖 Scenario: Imagine you are creating a simple Ruby class to represent a bank account. You want to control access to certain methods to protect sensitive information and actions.
🎯 Goal: You will build a Ruby class BankAccount that uses protected and private methods to control access to balance information and withdrawal actions.
📋 What You'll Learn
Create a class called BankAccount with an instance variable @balance
Add a protected method called display_balance that returns the balance
Add a private method called withdraw that subtracts an amount from the balance
Add a public method called transfer that uses withdraw and display_balance to transfer money between accounts
Print the balance of both accounts after the transfer
💡 Why This Matters
🌍 Real World
Controlling access to sensitive data and actions is important in real-world applications like banking software to prevent unauthorized access or changes.
💼 Career
Understanding method visibility is essential for writing secure and maintainable Ruby code, a skill valued in software development jobs.
Progress0 / 4 steps
1
Create the BankAccount class with initial balance
Create a class called BankAccount with an initialize method that sets an instance variable @balance to the value passed as a parameter.
Ruby
Need a hint?

Use def initialize(amount) and set @balance = amount.

2
Add a protected method to display balance
Inside the BankAccount class, add a protected method called display_balance that returns the value of @balance.
Ruby
Need a hint?

Use the protected keyword before defining def display_balance.

3
Add a private method to withdraw money
Inside the BankAccount class, add a private method called withdraw that takes an amount parameter and subtracts it from @balance.
Ruby
Need a hint?

Use the private keyword before defining def withdraw(amount).

4
Add a public transfer method and print balances
Add a public method called transfer that takes another BankAccount object and an amount. It should call withdraw(amount) on the current object and add the amount to the other account's @balance directly. Then, create two accounts, transfer 50 from the first to the second, and print both balances using display_balance.
Ruby
Need a hint?

Use withdraw(amount) to reduce balance, other_account.display_balance to get the other balance, and instance_variable_set to add to it. Use send(:display_balance) to print balances.