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 Part 4: Printing the register

Eliza SJ
Eliza SJ
4,587 Points

Getting an error for the print_register method

I'm following along with the video, but I'm getting an error when I try to run the code for the print_register method.

The error I'm getting: bank_account.rb:38:in print_register': undefined methodeach' for nil:NilClass (NoMethodError)

What exactly is the problem with my loop ? I'm at a total loss, I've been re-watching over and over to see where I could have made a mistake but as far as I can tell, it's the same code as in the video O.o ...

My code:

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)
        #push a hash into the array w/2 keys : description & amount)
        @transactions.push(description: description, amount: amount)
    end

    def balance
        balance = 0
        @transactions.each do |transaction|
            balance += transaction[:amount]
        end
        return balance
    end

    def to_s
        "Name: #{name}, Balance: #{sprintf("%0.2f", balance)}"
    end

    def print_register
        puts "#{name}'s Bank Account"
        puts "Description\tAmount"
        @transaction.each do |transaction|
            puts transaction[:description] + "\t" + sprintf("%0.2f", transaction[:amount])
        end

        puts "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
puts "Register:"
bank_account.print_register
rdaniels
rdaniels
27,258 Points

In def print_register, I think you need an "s" after transaction. Your variable is @transactions, with an "s"...

2 Answers

Seth Reece
Seth Reece
32,867 Points

You have a typo. You have @transaction.each do. Your array is declared at the top as @transactions.

Eliza SJ
Eliza SJ
4,587 Points

oh wow, that's a stupid mistake -.-* thanks guys!!