Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Objects and Classes Build a Bank Account Class Implement the balance Method

Why does transaction between the pipes and after += not have 's'?

In the following example....

class BankAccount
  attr_reader :name

  def initialize(name)
    @name = name
    @transactions = []
    add_transaction("Beginning Balance", 0)
  end

  def debit(description, amount)
    add_transaction(description, -amount)
  end

  def credit(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

WHY in def balance method does 'transaction' lose the 's'. Its not referred to/ stated elsewhere so why is there no error message?

Thanks, S

1 Answer

Hi Sara,

The transaction is a local variable that holds each member of the transactions array when the each loop goes round. It could be called t or dave and it would still work.

So, let's say the array has something like this:

  1. "Shopping", -£20
  2. "Petrol", -£50
  3. "Payday", £500

In the first iteration of the loop, transaction will hold the 0 element - so then balance += transaction[:amount] will subtract £20 from the balance. The loop then carries on, so next time round, the transaction local variable holds element 1 and so on.

So we've created a loop to iterate through each element of the array. At each iteration, the variable we've declared in the pipes, transaction, holds the element in the array that the loop has reached. Those values then get binned and updated with the next element's values. The array is unchanged and one-at-a-time, transaction holds every value contained in that array.

I hope that makes sense - do ask if it doesn't and I'll try to be clearer!

Steve.

That is a crystal clear explanation- big thanks!

No problem, Sara. Happy to help.

Have a great New Year's Eve!

Steve.