Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,107 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,863 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