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

Chris Edwards
Chris Edwards
8,163 Points

Why do I get a error of undefined local variable or method?

I am trying to recreate the bank account ruby file as the video go along. I am getting a

class BankAccount

        def initialize(name)
                @name = name
                @transactions = []
                add_transaction("Beginning Balnce",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
                @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"   
        end
end

bank_account = BankAccount.new("Jason")
bank_account.credit("Paycheck", 100)
bank_account.debit("Grocieries", 40)
puts bank_account.inspect
puts bank_account.balance
puts sprintf("%0.2f", bank_account.balance)
bank_account.print_register

The error is...

bank_account.rb:34:in `print_register': undefined local variable or method `name' for #<BankAccount:0x007f86cc96c7b0> (NameError)
    from bank_account.rb:44:in `<main>'

Any help would be great.

3 Answers

Owen Tran
Owen Tran
6,822 Points

add

attr_reader :name

to the top

or change name to @name everywhere else

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

You don't seem to have a reader for the :name attribute. You can see that line (line 2) shortly around 6:12.

Chris Edwards
Chris Edwards
8,163 Points

wow, my eyes just never picked that up.

Thanks!!