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 Foundations Ruby Core Enumerable

John Stoveld
John Stoveld
4,203 Points

Error on Jason's code : Line 24 : issue with inject.

So I am getting an error trying to mimic Jason's code.

Here is what it looks like his code is - typing it out so I might have missed something:

class BankAccount
    attr_reader :transactions
    include Enumerable

    def <=> (other_account)
        self.balance <=> other_account.balance
    end

    def initialize(name)
        @name = name
        @balance = balance
        @transactions = []
    end

    def deposit(amount)
        @transactions.push(amount)
    end

    def withdraw(amount)
        @transactions.push(-amount)
    end

    def balance
        @transactions.inject(0) { |sum, iterator| sum += iterator }
    end

    def each
        @transactions.each{|transaction| yield transaction}
    end
end

account1 = BankAccount.new("John Stoveld")
account1.deposit(100)
account1.withdraw(50)
account1.deposit(500)
account1.withdraw(21)

account1.each do |transaction|
    puts transaction
end

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Why does your code have @balance = balance? The video says @balance = 0 and it works fine when you do it like this.

John Stoveld
John Stoveld
4,203 Points

That was it.

Not sure why I had that.

Im at work answering calls and bouncing between classes. Just missed that.

Thanks.