1

I have an specific method that I would like to call so that I can see the balances for 'accounts'. The method is;

 def report_balances(accounts)
   accounts.each do |account|
    puts account.balance
   end
 end

I am not sure but I have either built the above method incorrectly or I am calling it incorrectly or maybe I have placed the method correctly in my code.

class BankAccount
  attr_reader :balance

  def initialize(balance)
    @balance = balance
  end

  def deposit(amount)
    @balance += amount if amount >= 0
  end

  def withdraw(amount)
    @balance -= amount if @balance >= amount
  end
end

class SavingsAccount < BankAccount
  attr_reader :number_of_withdrawals
  APY = 0.0017

  def initialize(balance)
    super(balance) # calls the parent method
    @number_of_withdrawals = 0 # then continues here
  end

  def end_of_month_closeout
    if @balance > 0
      interest_gained = (@balance * APY) / 12
      @balance += interest_gained
    end
    @number_of_withdrawals = 0
  end

 def report_balances(accounts)
  accounts.each do |account|
    puts account.balance
   end
 end

end

I would like to see the balances of the objects:

my_account = SavingsAccount.new(100)

and

account = BankAccount.new(2500)

by calling

'report_balances(accounts)'

How would this be accomplished?

1 Answer 1

1

Think of my_account = SavingsAccount.new(100) as creating a new account, but what you're asking is I want to see all the balances of a list of accounts. Since each account has a balance, you can do:

   [my_account, other_account].each do |account|
     puts account.balance
   end

I'd recommend moving your report_balances method to a class method or out of that class all together but that's a topic for a different discussion.

Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense, 'each do' has to do with arrays so now I see what Im doing wrong thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.