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!

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

How do I use the inject method instead of iteration in the bank account extra credit?

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

2 Answers

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,605 Points

Hi Ali

This is the solution I came up with:

    def balance_with_inject
        balance = @transactions.inject(0.0) do |sum, transaction| 
            sum + transaction[:amount] 
        end
        balance
    end

Instead of declaring a variable named balance as a float and then using it to accumulate the balance, I used the inject method on the @transactions array. I passed one argument to the inject method, the float 0.0; within the block I have two variables between vertical bars (|sum, transaction|) to work with. The first variable, sum, is assigned the float value passed to inject, 0.0, and is used in the same way you used the balance variable in your method (i.e. a way to hold the balance as you add it up). The second variable, transaction, will reference each transaction in succession and the value of each amount is accessed by its key. The inject method then returns a float object which is the sum of all transactions. Finally, I return the balance.

I hope that description isn't too confusing.

Tim Knight
Tim Knight
28,888 Points

Here's my attempt at using inject. This one creates an array of the transaction amounts. I think it could be simplified more, but it's my first iteration.

def balance
  amounts = []                                      # Creates an empty array
  @transactions.each { |t| amounts << t[:amount] }  # Iterates over transactions and pushes amount into array
  amounts.inject(:+) || 0.0                         # Adds amounts together, but if empty returns 0.0
end