Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Ruby Objects and Classes!
You have completed Ruby Objects and Classes!
Preview
In part 3 of Build a Bank Account class, we're going to calculate the balance based off of all of the transactions that exist within the account. We do this by writing a method called `balance`.
Code Samples
class BankAccount
attr_reader :name
def initialize(name)
@name = name
@transactions = []
add_transaction("Beginning Balance", 0)
end
def credit(description, amount)
add_transaction(description, amount)
end
def debit(description, amount)
add_transaction(description, -amount)
end
def add_transaction(description, amount)
@transactions.push(description: description, amount: amount)
end
def balance
balance = 0.0
@transactions.each do |transaction|
balance += transaction[:amount]
end
return balance
end
def to_s
"Name: #{name}, Balance: #{sprintf("%0.2f", balance)}"
end
end
bank_account = BankAccount.new("Jason")
bank_account.credit("Paycheck", 100)
bank_account.debit("Groceries", 40)
puts bank_account
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
So it would be nice to be able to see what
our balance is.
0:00
So let's go ahead and write a method that
calculates the balance for
0:03
us by looping through the transactions.
0:08
So we know that transactions is an array.
0:12
And in the Ruby Loops course,
0:14
we learned about iterating through arrays
with the each method.
0:16
Let's go ahead and use the each method to
iterate over the transactions and
0:20
add up the balance.
0:26
So, we can say @transactions.each do.
0:29
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up