Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
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 up-
Justin Sze Wei Teo
9,418 Points4 Answers
-
vo thi quynh yen
3,129 Points3 Answers
-
Unsubscribed User
11,042 Points1 Answer
-
Erik Nuber
20,629 Points1 Answer
-
Julia Fitzer
Front End Web Development Techdegree Student 5,574 Points1 Answer
-
Kaiyang Lin
5,573 Points1 Answer
-
Eliza SJ
4,587 PointsWhat is the purpose of 'return balance' ? What is 'return' actually doing ?
Posted by Eliza SJEliza SJ
4,587 Points2 Answers
-
Frank Kuester
3,002 Points1 Answer
-
Mohammed Ali
11,134 Points2 Answers
-
Adrian Manteza
2,527 Points4 Answers
-
4Ctech Admin
5,062 Points1 Answer
-
Rich S
1,936 Points@transactions.push(description: description, amount: amount) What's the purpose behind the colons?
Posted by Rich SRich S
1,936 Points1 Answer
View all discussions for this video
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
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